From 1400dc15060ebe5f4675c592bce4c885e6e5cee1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 19:52:06 +0900 Subject: [PATCH] =?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 @@ -