From 4f4bd1fd347396815dfd061de2bd8692e971908c Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Tue, 29 Sep 2026 13:39:24 +0900 Subject: [PATCH] =?UTF-8?q?review-followup=20Wave=203=20=EB=9D=BC=EC=9A=B4?= =?UTF-8?q?=EB=93=9C=203(P22):=20Redis=20runtime=C2=B7SDK=20=EB=B6=84?= =?UTF-8?q?=EB=A6=AC,=20=EC=A2=81=EC=9D=80=20semantic=20=ED=8F=AC=ED=8A=B8?= =?UTF-8?q?,=20startup=20rule,=20lease=20fencing=20=EA=B3=84=EC=95=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pub/sub 표면 삭제(G-6b·G-4i — 소비자 0, capability 규칙 3): SDK pub/sub·runtime gateway·PUBSUB lane·env 키 2개 - runtime을 `…cache.redis.runtime`으로(split package 해소), runtime은 소비자가 쓰는 8개 명령(`SemanticRedisCommands`)만, 118개 메서드 gateway는 redis-sdk가 확장. SDK의 blocking·transaction·admin lane은 코드로 조립(env 키 4개 삭제) - EVALSHA+NOSCRIPT 재로드 헬퍼 하나(메시지에만 NOSCRIPT가 온 경우도 재로드 — `LeaseScriptsTest` FAIL→PASS) - startup rule 목록 + runner 하나(환경 검사 8개, exit code·문구 유지), Redis secret 요구는 모듈이 기여, ratelimit 정책을 cache-redis 밖으로, lease fencing 계약 테스트(fake·어댑터·실제 Redis) - 통합: redis-sdk 테스트 2개가 옛 split package 경로를 보던 것 수정(ORCH-new-4) 검증: ./gradlew check architectureCheck verifyDependencyLocks :app-bootstrap:verifyEnvKeys configContractCheck :app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest --continue 통과(682 task), Redis 7.4 standalone topology lane: runtime 7 · sdk 14 · cache-redis 19, 실패·skip 0 Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/capability-status.md | 10 + docs/registries/env-keys.yaml | 115 +--- docs/registries/secrets-classification.yaml | 16 + .../W3-P22.md | 38 ++ .../2026-09-25-review-followup-status.md | 36 +- .../plans/2026-09-25-review-followup.md | 4 +- src/.env.example | 6 - src/adapter/outbound/cache-redis/CLAUDE.md | 63 +- src/adapter/outbound/cache-redis/README.md | 16 +- src/adapter/outbound/cache-redis/build.gradle | 8 +- .../cache/redis/RegisteredLuaScript.java | 179 ++++++ .../cache/redis/SemanticRedisCall.java | 168 +++++ .../cache/redis/cache/CacheScripts.java | 59 +- .../redis/cache/RedisCacheRegionAdapter.java | 237 +++----- .../redis/capability/RedisCacheConfig.java | 12 +- .../capability/RedisCapabilityConfig.java | 42 +- .../RedisCorrectnessRoleSelectors.java | 95 +++ .../capability/RedisIdempotencyConfig.java | 10 +- .../cache/redis/capability/RedisKeys.java | 17 +- .../redis/capability/RedisLeaseConfig.java | 10 +- .../capability/RedisProductionSecrets.java | 24 + .../capability/RedisRateLimitConfig.java | 16 +- .../RedisReadinessGroupPostProcessor.java | 2 +- .../RedisSemanticScriptAclProbe.java | 10 +- .../redis/idempotency/IdempotencyScripts.java | 177 +++--- .../RedisIdempotencyStoreAdapter.java | 520 +++++++--------- .../redis/keyspace/CapabilityKeyspace.java | 4 +- .../cache/redis/lease/LeaseScripts.java | 122 +--- .../lease/RedisDistributedLeaseAdapter.java | 292 ++++----- .../redis}/ratelimit/RateLimitAlgorithm.java | 2 +- .../RateLimitEvaluationDedupPolicy.java | 4 +- .../ratelimit/RateLimitFailurePolicy.java | 2 +- .../cache/redis/ratelimit/RateLimitKeys.java | 3 +- .../redis}/ratelimit/RateLimitPolicy.java | 17 +- .../ratelimit/RateLimitPolicyBounds.java | 70 +++ .../redis/ratelimit/RateLimitScripts.java | 114 +--- .../ratelimit/RedisEdgeRateLimitAdapter.java | 69 +-- .../main/resources/META-INF/spring.factories | 4 + .../cache/redis/LiveRedisRuntime.java | 28 +- .../redis/LiveRedisSemanticPortsTest.java | 20 +- .../cache/redis/RegisteredLuaScriptTest.java | 118 ++++ .../cache/RedisCacheRegionAdapterTest.java | 88 +-- .../LiveRedisSemanticScriptAclProbeTest.java | 4 +- .../RedisCapabilityActivationTest.java | 2 +- .../RedisCapabilityCompositionTest.java | 10 +- .../RedisProductionSecretsTest.java | 80 +++ .../RedisReadinessGroupPostProcessorTest.java | 17 +- .../RedisSemanticScriptAclProbeTest.java | 45 +- ...potencyScriptsConcurrencyContractTest.java | 29 - .../RedisIdempotencyStoreAdapterTest.java | 60 +- .../cache/redis/lease/LeaseScriptsTest.java | 53 ++ ...LiveRedisDistributedLeaseContractTest.java | 65 ++ .../RedisDistributedLeaseAdapterTest.java | 66 +- .../RedisDistributedLeaseContractTest.java | 45 ++ .../RateLimitEvaluationDedupPolicyTest.java | 2 +- .../redis}/ratelimit/RateLimitPolicyTest.java | 3 +- .../RedisEdgeRateLimitAdapterTest.java | 58 +- .../outbound/persistence-jpa/README.md | 4 +- .../startup/FlywayProdSafetyValidator.java | 60 +- .../HikariPoolConstraintValidator.java | 49 +- .../startup/JpaStartupAutoConfiguration.java | 26 +- .../startup/OpenInViewSafetyValidator.java | 44 +- .../PersistenceVendorProdSafetyValidator.java | 32 +- .../PostgreSqlTransportSecurityValidator.java | 41 +- .../startup/RequiredEnvironmentValidator.java | 39 +- .../FlywayProdSafetyValidatorTest.java | 6 +- .../HikariPoolConstraintValidatorTest.java | 6 +- .../OpenInViewSafetyValidatorTest.java | 6 +- ...sistenceVendorProdSafetyValidatorTest.java | 6 +- ...tgreSqlTransportSecurityValidatorTest.java | 6 +- .../RequiredEnvironmentValidatorTest.java | 6 +- .../api => runtime}/RedisDeploymentMode.java | 4 +- .../cluster/RedisSlotCalculator.java | 2 +- .../command/LettuceSemanticRedisCommands.java | 91 +++ .../command/SemanticRedisCommands.java | 96 +++ .../command}/WritePresence.java | 2 +- .../config/RedisAccountContribution.java | 30 + .../config/RedisCorrectnessRequirement.java | 30 + .../runtime/config/RedisCorrectnessRoles.java | 65 ++ .../config/RedisCredentialResolver.java | 2 +- .../config/RedisHealthContributor.java | 18 +- .../runtime/config/RedisLaneContribution.java | 25 + .../RedisRuntimeAutoConfiguration.java} | 137 +++-- .../config/RedisRuntimeSettings.java} | 126 +--- .../AccountRoutingRuntimeClient.java | 66 ++ .../connection/ClusterRuntimeClient.java | 84 +++ .../runtime/connection/LaneConnection.java | 37 ++ .../runtime/connection/RedisAccount.java | 46 ++ .../connection/RedisConnectionKind.java | 29 + .../connection/RedisDriverConnection.java | 49 ++ .../redis/runtime/connection/RedisLane.java | 45 ++ .../RedisLaneUnavailableException.java | 38 ++ .../connection/RedisLease.java | 30 +- .../connection/RedisRuntimeClient.java | 85 +++ .../connection/RedisRuntimeOwner.java | 114 ++-- .../RedisTopologyClientFactory.java | 339 +---------- .../connection/SharedClientResources.java | 60 ++ .../runtime/connection/ShutdownBudget.java | 32 + .../connection/StandaloneRuntimeClient.java | 56 ++ .../api => runtime}/key/RedisKeyRules.java | 2 +- .../api => runtime}/key/RedisNamespace.java | 2 +- .../sdk/config/RedisCorrectnessRoles.java | 86 --- .../connection/RedisConnectionKind.java | 75 --- .../connection/RedisCredentialRole.java | 30 - .../connection/RedisRuntimeClient.java | 83 --- .../operations/RedisPubSubGateway.java | 71 --- ...ot.autoconfigure.AutoConfiguration.imports | 2 +- .../RedisRuntimePackageBoundaryTest.java | 70 +++ .../config/LiveRedisCompositionTest.java | 24 +- .../config/LiveRedisTlsTest.java | 22 +- .../PropertyCorrectnessRequirement.java | 26 + .../config/RedisHealthContributorTest.java | 68 +-- ...imeAutoConfigurationRegistrationTest.java} | 9 +- .../RedisRuntimeAutoConfigurationTest.java} | 146 +++-- .../config/RedisRuntimeSettingsTest.java} | 46 +- .../config/RedisScriptLaneAdmissionTest.java | 63 +- .../config/RedisScriptLaneCapacityTest.java | 42 ++ .../config/RequiredWhenIsEnforcedTest.java | 11 +- .../connection/RedisRuntimeOwnerTest.java | 95 ++- .../config/RedisScriptLaneCapacityTest.java | 69 --- .../test/resources/META-INF/spring.factories | 3 + .../RedisTopologyEndpoint.java | 3 +- .../InMemorySemanticRedisCommands.java | 572 ++++++++++++++++++ .../connection/StubRedisRuntimeClient.java | 89 +++ .../operations/InMemoryGatewayAccess.java | 50 -- src/adapter/outbound/redis-sdk/README.md | 40 +- .../redis/sdk/api/RedisCapabilities.java | 1 + .../cache/redis/sdk/api/RedisCapability.java | 2 - .../cache/redis/sdk/api/RedisVersion.java | 0 .../redis/sdk/api/command/CommandAccess.java | 0 .../redis/sdk/api/command/CommandId.java | 0 .../redis/sdk/api/command/CommandSupport.java | 0 .../cache/redis/sdk/api/command/KeySpec.java | 0 .../sdk/api/command/PersistentKeyPermit.java | 0 .../api/command/RedisCommandDescriptor.java | 0 .../redis/sdk/api/command/RedisRiskLevel.java | 0 .../redis/sdk/api/command/TimeoutProfile.java | 0 .../error/RedisCommandRejectedException.java | 0 .../sdk/api/error/RedisFailureMetadata.java | 2 +- .../api/error/RedisOperationException.java | 0 .../redis/sdk/api/key/QualifiedRedisKey.java | 1 + .../cache/redis/sdk/api/key/RedisKeyName.java | 2 + .../redis/sdk/api/key/RedisKeyRenderer.java | 1 + .../cache/redis/sdk/api/key/RedisSlotTag.java | 2 + .../redis/sdk/api/key/TypedRedisKeys.java | 1 + .../sdk/api/operations/BitFieldOverflow.java | 0 .../api/operations/BitFieldSubcommand.java | 0 .../sdk/api/operations/BitmapOperation.java | 0 .../redis/sdk/api/operations/Distance.java | 0 .../sdk/api/operations/DistanceUnit.java | 0 .../redis/sdk/api/operations/Expiration.java | 0 .../api/operations/ExpirationCondition.java | 0 .../redis/sdk/api/operations/GeoPoint.java | 0 .../sdk/api/operations/GeoSearchRequest.java | 0 .../redis/sdk/api/operations/LexRange.java | 0 .../redis/sdk/api/operations/ListSide.java | 0 .../redis/sdk/api/operations/LongRange.java | 0 .../redis/sdk/api/operations/PageRequest.java | 0 .../sdk/api/operations/PubSubChannel.java | 37 -- .../sdk/api/operations/PubSubPattern.java | 42 -- .../api/operations/RedisPubSubOperations.java | 44 -- .../RedisShardedPubSubOperations.java | 33 - .../redis/sdk/api/operations/ScoreRange.java | 0 .../api/operations/ShardedPubSubChannel.java | 36 -- .../sdk/api/operations/SortDirection.java | 0 .../api/operations/SortedSetAddOptions.java | 0 .../api/operations/StreamAppendOptions.java | 0 .../sdk/api/operations/StreamConsumer.java | 2 +- .../api/operations/StreamDeletionOutcome.java | 0 .../api/operations/StreamDeletionPolicy.java | 0 .../redis/sdk/api/operations/StreamGroup.java | 2 +- .../redis/sdk/api/operations/StreamId.java | 0 .../sdk/api/operations/StreamTrimPolicy.java | 0 .../sdk/api/operations/Subscription.java | 27 - .../ReactiveRedisPubSubOperations.java | 44 -- .../ReactiveRedisShardedPubSubOperations.java | 29 - .../sdk/cluster/ClusterTopologyObserver.java | 1 + .../redis/sdk/cluster/SameSlotValidator.java | 3 +- .../config/ConfiguredRedisPermitVerifier.java | 2 +- .../sdk/config/RedisCapabilityProbe.java | 3 +- .../redis/sdk/config/RedisStartupProbe.java | 5 +- .../redis/sdk/lettuce/codec/DoubleCodec.java | 2 +- .../lettuce/codec/JsonEnvelopeFraming.java | 2 +- .../redis/sdk/lettuce/codec/LongCodec.java | 2 +- .../sdk/lettuce/codec/RedisCodecRegistry.java | 2 +- .../sdk/lettuce/codec/VersionedJsonCodec.java | 2 +- .../sdk/lettuce/command/CommandAdmission.java | 4 +- .../command/CommandExecutionContext.java | 2 +- .../lettuce/command/CommandPolicyGuard.java | 6 +- .../command/QueueingRedisCommandExecutor.java | 2 +- .../command/ReactiveRedisCommandExecutor.java | 2 +- .../lettuce/command/RedisCommandCatalog.java | 2 +- .../command/SyncRedisCommandExecutor.java | 2 +- .../connection/RedisSdkComposition.java | 88 +++ .../sdk/lettuce/connection/RedisSdkLane.java | 63 ++ .../observability/RedisObservation.java | 10 +- .../lettuce/operations/BatchExecution.java | 2 +- .../sdk/lettuce/operations/GeoSearchHit.java | 0 .../sdk/lettuce/operations/HashScanPage.java | 0 .../sdk/lettuce/operations/KeyScanPage.java | 0 .../sdk/lettuce/operations/KeyedElement.java | 0 .../LettuceReactiveRedisBatchOperations.java | 2 +- .../LettuceReactiveRedisPubSubOperations.java | 76 --- ...eReactiveRedisShardedPubSubOperations.java | 76 --- .../LettuceReactiveRedisValueOperations.java | 1 + .../lettuce/operations/LettuceRedisBatch.java | 1 + .../LettuceRedisBatchOperations.java | 2 +- .../LettuceRedisBlockingListOperations.java | 2 +- .../LettuceRedisBlockingStreamOperations.java | 4 +- .../LettuceRedisCommandGateway.java | 24 + .../LettuceRedisPubSubOperations.java | 100 --- .../LettuceRedisShardedPubSubOperations.java | 98 --- .../LettuceRedisValueOperations.java | 1 + .../lettuce/operations/LiveSubscription.java | 44 -- .../lettuce/operations/MemberScanPage.java | 0 .../sdk/lettuce/operations/PubSubCodecs.java | 43 -- .../operations/PubSubOperationRequests.java | 119 ---- .../operations/RedisCommandGateway.java | 33 +- .../operations/RedisOperationContext.java | 7 +- .../lettuce/operations/ScoredMemberPage.java | 0 .../lettuce/operations/StreamClaimPage.java | 0 .../sdk/lettuce/operations/StreamEntry.java | 0 .../operations/StreamPendingEntry.java | 0 .../operations/StreamPendingOverview.java | 0 .../lettuce/operations/SubscriptionFlux.java | 163 ----- .../operations/ValueOperationRequests.java | 1 + .../LettuceRedisTransactionOperations.java | 4 +- .../RedisTransactionRunner.java | 33 +- .../redis-sdk/redis-command-policy.yml | 19 +- .../redis/sdk/RedisSdkModuleBoundaryTest.java | 7 +- .../redis/sdk/RedisSupportMatrixTest.java | 7 +- .../redis/sdk/RedisTopologyContractTest.java | 1 + .../cache/redis/sdk/api/ApiParityTest.java | 9 +- .../redis/sdk/api/RedisCapabilitiesTest.java | 3 +- .../cache/redis/sdk/api/RedisVersionTest.java | 0 .../sdk/api/key/RedisKeyRendererTest.java | 2 + .../redis/sdk/api/key/RedisKeyRulesTest.java | 1 + .../sdk/cluster/RedisSlotCalculatorTest.java | 5 +- .../sdk/config/RedisCapabilityProbeTest.java | 4 +- .../sdk/config/RedisPermitProvenanceTest.java | 2 +- .../sdk/config/RedisStartupProbeTest.java | 8 +- .../lettuce/codec/RedisCodecRegistryTest.java | 2 +- .../lettuce/codec/VersionedJsonCodecTest.java | 2 +- .../command/CommandPolicyGuardTest.java | 14 +- .../command/ObservationIsolationTest.java | 8 +- .../observability/RedisObservationTest.java | 4 +- .../InMemoryRedisCommandGateway.java | 390 +----------- .../InMemoryRedisPubSubGateway.java | 111 ---- .../operations/LiveRedisClusterTest.java | 4 +- .../operations/LiveRedisGuardrailTest.java | 2 +- .../LiveRedisOperationsFixture.java | 9 +- .../LiveRedisSentinelPromotionTest.java | 2 +- .../RedisAdminPlaneContractTest.java | 2 +- .../RedisExtensionModulesContractTest.java | 2 +- .../operations/RedisOperationsFixture.java | 21 +- .../RedisPubSubOperationsContractTest.java | 201 ------ .../RedisRawGatewayContractTest.java | 2 +- .../RedisScriptOperationsContractTest.java | 2 +- .../RedisTransactionContractTest.java | 8 +- .../RedisTransactionSlotContractTest.java | 8 +- .../LiveRedisClusterTransactionTest.java | 34 +- .../startup/RequiredProductionSecrets.java | 24 + .../outbound/support/startup/StartupRule.java | 51 ++ .../startup/StartupRuleAutoConfiguration.java | 27 + .../support/startup/StartupRuleRunner.java | 53 ++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../startup/StartupRuleRunnerTest.java | 94 +++ src/app-bootstrap/CLAUDE.md | 5 + src/app-bootstrap/README.md | 11 + .../ErrorDetailExposureSafetyValidator.java | 30 +- .../RuntimeNumericBoundsValidator.java | 30 +- .../runtime/RuntimeSafetyConfig.java | 9 +- .../bootstrap/runtime/SecretSourceConfig.java | 9 +- .../runtime/SecretSourceValidator.java | 104 +--- ...rrorDetailExposureSafetyValidatorTest.java | 6 +- .../RuntimeNumericBoundsValidatorTest.java | 6 +- .../runtime/SecretSourceValidatorTest.java | 199 +----- .../InMemoryDistributedLeaseContractTest.java | 21 + .../testkit/DistributedLeaseContract.java | 188 ++++++ .../testkit/InMemoryDistributedLease.java | 202 +++++++ src/shared-contract/README.md | 7 +- .../shared/ratelimit/RateLimitBounds.java | 2 - ...eRateLimitProviderNeutralContractTest.java | 41 -- 283 files changed, 5499 insertions(+), 5120 deletions(-) create mode 100644 docs/reviews/2026-09-25-review-followup-results/W3-P22.md create mode 100644 src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScript.java create mode 100644 src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCall.java create mode 100644 src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCorrectnessRoleSelectors.java create mode 100644 src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecrets.java rename src/{shared-contract/src/main/java/dev/caskeleton/shared => adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis}/ratelimit/RateLimitAlgorithm.java (57%) rename src/{shared-contract/src/main/java/dev/caskeleton/shared => adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis}/ratelimit/RateLimitEvaluationDedupPolicy.java (93%) rename src/{shared-contract/src/main/java/dev/caskeleton/shared => adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis}/ratelimit/RateLimitFailurePolicy.java (67%) rename src/{shared-contract/src/main/java/dev/caskeleton/shared => adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis}/ratelimit/RateLimitPolicy.java (92%) create mode 100644 src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScriptTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecretsTest.java delete mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScriptsConcurrencyContractTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScriptsTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LiveRedisDistributedLeaseContractTest.java create mode 100644 src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseContractTest.java rename src/{shared-contract/src/test/java/dev/caskeleton/shared => adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis}/ratelimit/RateLimitEvaluationDedupPolicyTest.java (96%) rename src/{shared-contract/src/test/java/dev/caskeleton/shared => adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis}/ratelimit/RateLimitPolicyTest.java (98%) rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/api => runtime}/RedisDeploymentMode.java (91%) rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/cluster/RedisSlotCalculator.java (97%) create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/LettuceSemanticRedisCommands.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/SemanticRedisCommands.java rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/lettuce/operations => runtime/command}/WritePresence.java (85%) create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisAccountContribution.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRequirement.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRoles.java rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/RedisCredentialResolver.java (98%) rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/RedisHealthContributor.java (90%) create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneContribution.java rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/config/RedisSdkAutoConfiguration.java => runtime/config/RedisRuntimeAutoConfiguration.java} (74%) rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/config/RedisSdkSettings.java => runtime/config/RedisRuntimeSettings.java} (84%) create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/AccountRoutingRuntimeClient.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ClusterRuntimeClient.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/LaneConnection.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisAccount.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisConnectionKind.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisDriverConnection.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLane.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneUnavailableException.java rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/lettuce => runtime}/connection/RedisLease.java (51%) create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeClient.java rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/lettuce => runtime}/connection/RedisRuntimeOwner.java (77%) rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/lettuce => runtime}/connection/RedisTopologyClientFactory.java (55%) create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/SharedClientResources.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ShutdownBudget.java create mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StandaloneRuntimeClient.java rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/api => runtime}/key/RedisKeyRules.java (98%) rename src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/api => runtime}/key/RedisNamespace.java (93%) delete mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCorrectnessRoles.java delete mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionKind.java delete mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java delete mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeClient.java delete mode 100644 src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubGateway.java create mode 100644 src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisRuntimePackageBoundaryTest.java rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/LiveRedisCompositionTest.java (89%) rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/LiveRedisTlsTest.java (86%) create mode 100644 src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/PropertyCorrectnessRequirement.java rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/RedisHealthContributorTest.java (64%) rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/config/RedisSdkAutoConfigurationRegistrationTest.java => runtime/config/RedisRuntimeAutoConfigurationRegistrationTest.java} (92%) rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/config/RedisSdkAutoConfigurationTest.java => runtime/config/RedisRuntimeAutoConfigurationTest.java} (71%) rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/config/RedisSdkSettingsTest.java => runtime/config/RedisRuntimeSettingsTest.java} (78%) rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/RedisScriptLaneAdmissionTest.java (69%) create mode 100644 src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/config/RequiredWhenIsEnforcedTest.java (93%) rename src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk/lettuce => runtime}/connection/RedisRuntimeOwnerTest.java (73%) delete mode 100644 src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java create mode 100644 src/adapter/outbound/redis-runtime/src/test/resources/META-INF/spring.factories rename src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/{sdk => runtime}/RedisTopologyEndpoint.java (98%) create mode 100644 src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java create mode 100644 src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StubRedisRuntimeClient.java delete mode 100644 src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersion.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandAccess.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandId.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandSupport.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/KeySpec.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/PersistentKeyPermit.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisCommandDescriptor.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisRiskLevel.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/TimeoutProfile.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisCommandRejectedException.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java (98%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisOperationException.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldOverflow.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldSubcommand.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitmapOperation.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Distance.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/DistanceUnit.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Expiration.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationCondition.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoPoint.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoSearchRequest.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LexRange.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ListSide.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LongRange.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PageRequest.java (100%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubChannel.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubPattern.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisPubSubOperations.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisShardedPubSubOperations.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ScoreRange.java (100%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ShardedPubSubChannel.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortDirection.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortedSetAddOptions.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamAppendOptions.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionOutcome.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionPolicy.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamId.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamTrimPolicy.java (100%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Subscription.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisPubSubOperations.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisShardedPubSubOperations.java create mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkComposition.java create mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkLane.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/GeoSearchHit.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/HashScanPage.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyScanPage.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyedElement.java (100%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisPubSubOperations.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisShardedPubSubOperations.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java (97%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisPubSubOperations.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisShardedPubSubOperations.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveSubscription.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/MemberScanPage.java (100%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubCodecs.java delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubOperationRequests.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java (97%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ScoredMemberPage.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamClaimPage.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamEntry.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingEntry.java (100%) rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingOverview.java (100%) delete mode 100644 src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/SubscriptionFlux.java rename src/adapter/outbound/{redis-runtime => redis-sdk}/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java (100%) rename src/adapter/outbound/{redis-runtime/src/testFixtures => redis-sdk/src/test}/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java (81%) delete mode 100644 src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java delete mode 100644 src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredProductionSecrets.java create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java create mode 100644 src/application-core/src/test/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLeaseContractTest.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/DistributedLeaseContract.java create mode 100644 src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLease.java diff --git a/docs/capability-status.md b/docs/capability-status.md index a5d2aac8..9df0b3c4 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -487,3 +487,13 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | untyped `DefaultDeliveryProcessor(Function, HandleResult>, …)` 생성자 | `src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultDeliveryProcessor.java` | `423a29c4` | typed `MessageHandler` 목록을 받는 형태로 교체(S7-#2) | | `CapabilityTier` (→ `ApiTier`로 개명), `CompatibilityMatrix.Tier` (→ `SupportGrade`) | `src/messaging/messaging-policy/src/main/java/dev/caskeleton/messaging/policy/CapabilityTier.java`, `src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/CompatibilityMatrix.java` | `423a29c4` | 등급 용어 정리(S7-#14) | | `api 'io.projectreactor:reactor-core'`, `testImplementation 'io.projectreactor:reactor-test'` | `src/messaging/messaging-spring-boot-starter/build.gradle` | `423a29c4` | reactive facade 삭제로 노출 이유 소멸(S7-#9c) | +| SDK pub/sub 연산 표면(`RedisPubSubOperations`, `RedisShardedPubSubOperations`, `ReactiveRedisPubSubOperations`, `ReactiveRedisShardedPubSubOperations`, `PubSubChannel`, `PubSubPattern`, `ShardedPubSubChannel`, `Subscription`, `LettuceRedisPubSubOperations`, `LettuceRedisShardedPubSubOperations`, `LettuceReactiveRedisPubSubOperations`, `LettuceReactiveRedisShardedPubSubOperations`, `LiveSubscription`, `PubSubCodecs`, `PubSubOperationRequests`, `SubscriptionFlux`)과 테스트 `InMemoryRedisPubSubGateway`·`RedisPubSubOperationsContractTest` | `src/adapter/outbound/redis-sdk/src/{main,test}/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/{api/operations,api/reactive,lettuce/operations}/` | `423a29c4` | 전송(`RedisPubSubGateway`) main 구현이 없어 동작 불가(G-6b) | +| `RedisPubSubGateway`, `RedisConnectionKind.PUBSUB`, `RedisCredentialRole.PUBSUB` | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/{operations,connection}/` | `423a29c4` | 위와 같음 | +| `RedisSdkSettings.PubSub`·`Authentication.pubsubCredentialReference`, env 키 `APP_REDIS_PUBSUB_BUFFER_CAPACITY`·`APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE` | `src/adapter/outbound/redis-runtime/.../sdk/config/RedisSdkSettings.java`, `docs/registries/env-keys.yaml`, `src/.env.example` | `423a29c4` | 동작하지 않는 옵션은 키를 두지 않는다(G-4i) | +| `RedisCapability.SHARDED_PUBSUB`, `RedisOperationContext.PATTERN_SUBSCRIBE` | `src/adapter/outbound/redis-sdk/.../sdk/api/RedisCapability.java`, `.../sdk/lettuce/operations/RedisOperationContext.java` | `423a29c4` | 사용처(pub/sub 연산) 삭제 | +| `RedisCredentialRole`(enum) | `src/adapter/outbound/redis-runtime/.../sdk/lettuce/connection/RedisCredentialRole.java` | `423a29c4` | 열린 `RedisAccount` 값으로 대체 — runtime은 자기 계정 2개만 알고 SDK가 admin 계정을 기여(G-7c) | +| `RedisSdkSettings.Blocking`·`Transaction`·`Admin`과 env 키 `APP_REDIS_ADMIN_ENABLED`·`APP_REDIS_ADMIN_CREDENTIAL_REFERENCE`·`APP_REDIS_BLOCKING_MAX_CONNECTIONS`·`APP_REDIS_TRANSACTION_MAX_CONNECTIONS` | `src/adapter/outbound/redis-runtime/.../sdk/config/RedisSdkSettings.java`, `docs/registries/env-keys.yaml`, `src/.env.example` | `423a29c4` | SDK 전용 lane·계정. SDK `RedisSdkComposition` 코드 설정으로 이동(G-7c, S3-#3b) | +| `InMemoryGatewayAccess` | `src/adapter/outbound/redis-runtime/src/testFixtures/.../sdk/lettuce/operations/InMemoryGatewayAccess.java` | `423a29c4` | cache-redis 테스트는 runtime testFixtures `InMemorySemanticRedisCommands`를 직접 쓴다. semantic 스크립트 에뮬레이션은 그 fake로 이동(SDK의 `InMemoryRedisCommandGateway`에서는 제거) | +| `IdempotencyScriptsConcurrencyContractTest` | `src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/` | `423a29c4` | reflection으로 `digests` Map 구조를 고정하던 테스트. 슬롯이 `RegisteredLuaScript` final 필드가 되어 대상이 없음; 동작은 `RegisteredLuaScriptTest`가 검증 | +| `SecretSourceValidator.REDIS_ENABLED_PROPERTY`와 Redis 역할 prefix 분기(`isRedisMaterial`, `isRedisRoleSelected`, `isRedisCacheBound`, `isSelected`), `REQUIRED_PROD_SECRETS`의 Redis 8개 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java` | `423a29c4` | cache-redis `RedisProductionSecrets`가 기여(S6-#2c) | +| shared `RateLimitBounds.MAXIMUM_CLEANUP_GRACE`·`MAXIMUM_CLOCK_REGRESSION`, `EdgeRateLimitProviderNeutralContractTest.allPortableAlgorithmsHaveBoundedProviderNeutralPolicies` | `src/shared-contract/src/{main,test}/java/dev/caskeleton/shared/ratelimit/` | `423a29c4` | 정책 타입이 cache-redis로 이동(S1-#15c). 정책 검증 테스트는 이동한 `RateLimitPolicyTest`에 있음 | diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 3529a148..4b717e27 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1207,7 +1207,7 @@ env_keys: # APP_SERVER_FORWARD_HEADERS_STRATEGY=native and server.tomcat.remoteip.internal-proxies. - name: APP_RATE_LIMIT_REDIS_ENABLED - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.enabled (APP_REDIS_ENABLED). deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1295,7 +1295,7 @@ env_keys: required_test: rate-limit-contract:key-version-bounded - name: APP_RATE_LIMIT_REDIS_HOST - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.nodes (APP_REDIS_NODES). deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1311,7 +1311,7 @@ env_keys: required_test: rate-limit-contract:redis-host-required - name: APP_RATE_LIMIT_REDIS_PORT - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.nodes (APP_REDIS_NODES). deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1339,7 +1339,7 @@ env_keys: required_test: rate-limit-contract:redis-password-no-leak - name: APP_RATE_LIMIT_REDIS_TRUST_PEM - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.tls.trust-material-resource. deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1424,7 +1424,7 @@ env_keys: required_test: rate-limit-contract:redis-timeout-bounded - name: APP_RATE_LIMIT_REDIS_MAXIMUM_COMMAND_BYTES - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.limits.max-batch-request-bytes. deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1440,7 +1440,7 @@ env_keys: required_test: rate-limit-contract:redis-command-bytes-bounded - name: APP_RATE_LIMIT_REDIS_MAXIMUM_QUEUED_COMMANDS - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.capacity.maximum-in-flight-commands. deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1456,7 +1456,7 @@ env_keys: required_test: rate-limit-contract:redis-queue-bounded - name: APP_RATE_LIMIT_REDIS_MAXIMUM_IN_FLIGHT_BYTES - # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisSdkAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. + # DEPRECATED 2026-08-10: the rate limiter no longer owns a Redis client of its own. One client, built by RedisRuntimeAutoConfiguration, serves every capability, so a second endpoint and a second set of ceilings could only ever disagree with it. # Replaced by: app.redis.capacity.maximum-in-flight-bytes. deprecated_orphaned: true removal_deadline: 2026-11-30 @@ -1842,57 +1842,12 @@ env_keys: compatibility_impact: additive required_test: redis-capability:lease-composition - # --- Redis SDK typed settings (app.redis.*) ------------------------------- - # Bound only by RedisSdkAutoConfiguration in adapter-outbound-redis-runtime while + # --- Redis runtime settings (app.redis.*) ---------------------------------- + # Bound only by RedisRuntimeAutoConfiguration in adapter-outbound-redis-runtime while # APP_REDIS_ENABLED is true. application.yml does not force these values into Redis-free # deployments; src/.env.example merely documents explicit operator inputs. verifyEnvKeys checks # the registry against the runtime module's configuration metadata. - - name: APP_REDIS_ADMIN_CREDENTIAL_REFERENCE - property: app.redis.admin.credential-reference - owner_module: adapter-outbound-redis-runtime - type: string - default: null - allowed_values: null - classification: sensitive-config - required: false - required_when: app.redis.admin.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: nonblank_when_required - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_ADMIN_ENABLED - property: app.redis.admin.enabled - owner_module: adapter-outbound-redis-runtime - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: boolean_strict - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_BLOCKING_MAX_CONNECTIONS - property: app.redis.blocking.max-connections - owner_module: adapter-outbound-redis-runtime - type: integer - default: 32 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_DATABASE # Cluster supports database 0 only; a non-zero value fails startup there. property: app.redis.database @@ -2032,24 +1987,8 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_TRANSACTION_MAX_CONNECTIONS - property: app.redis.transaction.max-connections - owner_module: adapter-outbound-redis-runtime - type: integer - default: 16 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - # --- Redis runtime composition settings (app.redis.*) ---------------------- - # Authentication, Sentinel discovery, TLS, lifecycle, Cluster routing, capacity and - # subscription delivery. Same rule as the rest of app.redis.*: bound only while + # Authentication, Sentinel discovery, TLS, lifecycle, Cluster routing and capacity. Same rule as the rest of app.redis.*: bound only while # APP_REDIS_ENABLED is true, and deliberately absent from application.yml and .env. - name: APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE @@ -2103,21 +2042,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE - property: app.redis.authentication.pubsub-credential-reference - owner_module: adapter-outbound-cache-redis - type: string - default: null - allowed_values: null - classification: sensitive-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: nonblank_when_required - compatibility_impact: additive - required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_COMMANDS property: app.redis.capacity.maximum-in-flight-commands owner_module: adapter-outbound-cache-redis @@ -2287,21 +2211,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_PUBSUB_BUFFER_CAPACITY - property: app.redis.pubsub.buffer-capacity - owner_module: adapter-outbound-cache-redis - type: integer - default: 1024 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_SENTINEL_CREDENTIAL_REFERENCE property: app.redis.sentinel.credential-reference owner_module: adapter-outbound-cache-redis @@ -2379,8 +2288,8 @@ env_keys: classification: sensitive-config required: false # A relationship between two settings rather than a switch: a client certificate without its - # key cannot build a key manager. Enforced in RedisSdkSettings.validate and covered by - # RedisSdkSettingsTest, which is where the registry's prose conditions are proven. + # key cannot build a key manager. Enforced in RedisRuntimeSettings.validate and covered by + # RedisRuntimeSettingsTest, which is where the registry's prose conditions are proven. required_when: app.redis.tls.client-certificate-resource is configured reload_policy: restart-only owner_branch: redis-optionality-and-composition diff --git a/docs/registries/secrets-classification.yaml b/docs/registries/secrets-classification.yaml index a0225652..933bde7f 100644 --- a/docs/registries/secrets-classification.yaml +++ b/docs/registries/secrets-classification.yaml @@ -54,6 +54,8 @@ secrets: source: secret-manager rotation_policy: restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.capabilities.cache.bindings.default=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: feature-secrets-config-source-contract masking_rule: full @@ -78,6 +80,8 @@ secrets: source: secret-manager rotation_policy: dual-read-restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.capabilities.cache.bindings.default=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: codex-phase-a-ci-recovery masking_rule: full @@ -90,6 +94,8 @@ secrets: source: secret-manager rotation_policy: restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.capabilities.rate-limit.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-distributed-rate-limit masking_rule: full @@ -114,6 +120,8 @@ secrets: source: secret-manager rotation_policy: dual-read-restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.capabilities.rate-limit.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-distributed-rate-limit masking_rule: full @@ -126,6 +134,8 @@ secrets: source: secret-manager rotation_policy: restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.security.auth-mode=redis-session dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability masking_rule: full @@ -150,6 +160,8 @@ secrets: source: secret-manager rotation_policy: dual-read-restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.security.auth-mode=redis-session dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability masking_rule: full @@ -162,6 +174,8 @@ secrets: source: secret-manager rotation_policy: cold-cutover-restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.capabilities.idempotency.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability-completion masking_rule: full @@ -174,6 +188,8 @@ secrets: source: secret-manager rotation_policy: cold-cutover-restart-only prod_default: null + # Required with app.redis.enabled=true and this role selected; checked by adapter-outbound-cache-redis RedisProductionSecrets. + required_when: ca-skeleton.capabilities.lease.provider=redis dev_sentinel_prefix: __LOCAL_DEV_ owner_branch: redis-production-capability-completion masking_rule: full diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P22.md b/docs/reviews/2026-09-25-review-followup-results/W3-P22.md new file mode 100644 index 00000000..710b20c3 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P22.md @@ -0,0 +1,38 @@ +## 행 결과 +| ID | 결과 | 근거 | +|---|---|---| +| G-4i | 해당 없음(코드 삭제) | P22 D `1b3138cb`: `RedisSdkSettings.PubSub`·`Authentication.pubsubCredentialReference`, env 키 `APP_REDIS_PUBSUB_BUFFER_CAPACITY`·`APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE`(`docs/registries/env-keys.yaml`·`src/.env.example`) 삭제. `:app-bootstrap:verifyEnvKeys` 통과 | +| G-6b | 해당 없음(코드 삭제) | P22 D `1b3138cb`. **구현 대신 삭제를 택함**: 구현하려면 Lettuce pub/sub 연결 수명·버퍼 한도·재구독·sharded 라우팅·실제 벤더 lane을 새로 만들어야 하고(capability 규칙 3 "켜면 완전히 동작"), main 소비자가 0이다. 삭제는 SDK 파일 18개와 runtime 인터페이스 1개로 끝난다. 카탈로그 `redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml:745-780`의 PUBLISH/SUBSCRIBE/PSUBSCRIBE/SPUBLISH… 8개는 `BLOCKED`(카탈로그는 서버의 모든 명령을 판정해야 하므로 행은 남김), `RedisCapability.SHARDED_PUBSUB`·`pattern-subscribe` permit 정책 삭제, `redis-sdk/README.md` 표에서 pub/sub 제거 | +| G-7a | 완료 | P22 W1 `bd0e0bc6`. runtime 계약은 `redis-runtime/.../runtime/command/SemanticRedisCommands.java:19`(get·set(Duration)·getAndDelete·incrementBy·ping·loadScript·evaluateRegisteredForList/Long 8개)와 구현 `LettuceSemanticRedisCommands`. 118개 메서드 `RedisCommandGateway`와 `LettuceRedisCommandGateway`는 redis-sdk로 이동해 `redis-sdk/.../sdk/lettuce/operations/RedisCommandGateway.java:48`에서 `SemanticRedisCommands`를 확장하고, 빌린 연결의 `RedisLease.driver()`로 `LettuceRedisCommandGateway.over(...)`를 만든다. `api.command`·`api.error`·`api.operations`·`RedisVersion`·페이지 타입도 SDK로. cache-redis·health는 8개만 사용 | +| G-7c | 완료 | P22 W1 `bd0e0bc6`. runtime lane은 `RedisConnectionKind.java:12-16` REGULAR·SCRIPT만. BLOCKING·TRANSACTION·ADMIN은 `redis-sdk/.../sdk/lettuce/connection/RedisSdkLane.java:19`, admin 계정과 lane 한도는 `RedisSdkComposition.java`(서비스가 `RedisLaneContribution`·`RedisAccountContribution` 빈으로 기여, runtime `RedisRuntimeAutoConfiguration`이 모아 풀·자격 증명을 만든다). `app.redis.admin.*`·`app.redis.blocking.max-connections`·`app.redis.transaction.max-connections` 설정과 env 키 4개 삭제 — SDK의 다른 설정처럼 코드 설정(README "configuration that is code")으로. 테스트 `RedisRuntimeAutoConfigurationTest.configuredAccountsAreResolvedPerRole`(기여 계정 해석)·`aLaneAnotherModuleContributesIsPooledByTheOwner`·`aLaneComposedTwiceFailsTheContext` | +| G-7d | 완료 | P22 W1 `bd0e0bc6`. redis-runtime 전 파일이 `dev.caskeleton.adapter.outbound.cache.redis.runtime.*`(`RedisDeploymentMode`, `key`, `cluster`, `command`, `connection`, `config`). split package 해소. `RedisRuntimePackageBoundaryTest.noRuntimeSourceReferencesTheTypedSdkPackage`. SDK 쪽 `RedisSdkModuleBoundaryTest`는 SDK root만 스캔 | +| G-7e | 완료 | P22 W1 `bd0e0bc6`. selector 표는 `cache-redis/.../capability/RedisCorrectnessRoleSelectors.java:48`(W2에서 역할별 secret까지 한 표로)로 옮기고 cache-redis `META-INF/spring.factories`에 `RedisCorrectnessRequirement`로 등록. runtime `RedisCorrectnessRoles.java:44`는 등록된 요구에 "required 여부"만 묻는다. `RedisRuntimeAutoConfigurationTest.withoutARequirementTheRuntimeCreatesNoRequiredContributor`(runtime은 selector를 모른다)·`aModuleThatNeedsRedisForCorrectnessGetsTheRequiredContributor`, `RedisReadinessGroupPostProcessorTest.eachCorrectnessSelectorAppendsRedisReadiness`, live `LiveRedisCompositionTest` 스크립트 role 2건 통과 | +| G-8 | 완료 | P22 W1 `bd0e0bc6`: `cache-redis/.../RegisteredLuaScript.java:29`(digest 캐시·NOSCRIPT 판별 `:114`·재로드 1회·응답 디코딩)을 Cache/RateLimit/Lease/IdempotencyScripts 4곳이 사용. `LeaseScriptsTest.aProgramTheServerForgotIsReloadedEvenWhenOnlyTheMessageSaysNoScript` FAIL(`CompletionException` caused by `RedisCommandExecutionException` — 메시지로만 온 NOSCRIPT를 lease가 재로드하지 않음)→PASS. `RegisteredLuaScriptTest` 4건 | +| X1-지도-lock / lease / fencing | 완료 | 소유자 결정 8대로 lock·lease 포트 유지. claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog`는 이미 `208077fd`에서 삭제돼 남은 미사용 포트 없음. fencing은 contract kit로(P22 W2 `7f39bfda`): `application-core/src/testFixtures/.../lease/testkit/DistributedLeaseContract.java`(밀려난 holder의 renew·release는 NotOwner이고 후임의 lease를 건드리지 않는다, 같은 attempt 재acquire는 replay, 이중 release는 AlreadyAbsent — 7건)를 fake `InMemoryDistributedLease`(`InMemoryDistributedLeaseContractTest`), Redis 어댑터+in-memory 명령(`RedisDistributedLeaseContractTest`), 실제 Redis(`LiveRedisDistributedLeaseContractTest`, standalone lane)가 모두 통과. lock 포트의 공통 계약(JDBC 어댑터 포함)은 Wave 4 범위로 남김 | +| S1-#15c | 완료 | P22 W2 `7f39bfda`: `RateLimitPolicy`·`RateLimitAlgorithm`·`RateLimitEvaluationDedupPolicy`(+ 이들만 쓰는 `RateLimitFailurePolicy`)와 테스트 2개를 `cache-redis/.../ratelimit/`로 이동, 정책 검증 bounds는 `RateLimitPolicyBounds`(package-private). shared에는 `EdgeRateLimitPort`·`RateLimitRequest`·`RateLimitOutcome`·`RateLimitDecision`·`RateParameters`·subject 계열만 남음. `:shared-contract:check`·`:adapter:inbound:web:check` 통과 | +| S3-#3a | 완료 | = G-7a·G-7c. runtime 계약 8개, 나머지는 SDK 확장 인터페이스, lane은 REGULAR·SCRIPT, `forCommand(RedisCommandDescriptor)`는 SDK `RedisSdkLane.forCommand`로 | +| S3-#3b | 완료 | = G-7d. `RedisSdkSettings`→`RedisRuntimeSettings`, `RedisSdkAutoConfiguration`→`RedisRuntimeAutoConfiguration`, SDK 전용 섹션(blocking·transaction·admin)은 runtime 설정에서 빠지고 SDK 코드 설정으로. `RedisRuntimePackageBoundaryTest.noRuntimeTypeIsNamedAfterTheSdk` | +| S3-#4b | 완료 | P22 W1 `bd0e0bc6`: `cache-redis/.../SemanticRedisCall.java:35` — 빌림·bounded wait·not-sent/unknown 판정 한 곳(`effect`: 스크립트, `run`+`markSent`: cache). 네 어댑터의 `catch (InterruptedException` 15곳이 사라지고 cache-redis main에는 `SemanticRedisCall`과 시작 probe만 남음. Lua 응답 디코딩은 `RegisteredLuaScript.number/text/requireShape`. 기존 어댑터 테스트(`RedisIdempotencyStoreAdapterTest`·`RedisDistributedLeaseAdapterTest`·`RedisEdgeRateLimitAdapterTest`·`RedisCacheRegionAdapterTest`)와 live `LiveRedisSemanticPortsTest` 10건 통과 | +| S3-#5 | 완료 | P22 W1 `bd0e0bc6`: `IdempotencyScripts.ScriptStatus`(`IdempotencyScripts.java:228`)로 한 번 파싱, switch는 enum, `transition(...)`은 `Transition` record + `Map`(`RedisIdempotencyStoreAdapter.java:428`) — 인자 16개→7개 | +| S3-#9 | 완료 | P22 W1 `bd0e0bc6`: `RedisTopologyClientFactory` 662→371줄. `StandaloneRuntimeClient`·`ClusterRuntimeClient`·`AccountRoutingRuntimeClient`·`SharedClientResources`·`LaneConnection`·`ShutdownBudget`를 package-private top-level로 | +| S6-#2c | 완료 | P22 W2 `7f39bfda`: Redis 역할별 secret 판정은 `cache-redis/.../capability/RedisProductionSecrets.java`가 `RedisCorrectnessRoleSelectors.ROLES`(역할·selector·required·scripted·secret 한 표)에서 파생해 `support.startup.RequiredProductionSecrets` 빈으로 기여(Redis가 켜졌을 때만 존재). `SecretSourceValidator`는 `REQUIRED_PROD_SECRETS`(datasource·pseudonymization salt) + 모듈 기여 목록만 검사하고 `REDIS_ENABLED_PROPERTY`·역할 prefix 분기 삭제. 레지스트리 `secrets-classification.yaml`의 Redis secret 8행에 `required_when`. 테스트 `RedisProductionSecretsTest`(역할별 5 + 비선택 2), `SecretSourceValidatorTest.aSecretAModuleContributedIsRequiredInProd` 외 2건, `SecretsClassificationRegistryTest` 통과 | +| S6-#3a | 완료 | P22 W2 `7f39bfda`: `support.startup.StartupRule { phase(); summary(); remedy(); List violations(Environment) }` + 러너 하나 `StartupRuleRunner`(`StartupRuleAutoConfiguration`, support `AutoConfiguration.imports`). 환경만 읽는 검사 8개를 규칙으로: bootstrap `RuntimeNumericBoundsValidator`·`ErrorDetailExposureSafetyValidator`, persistence-jpa `RequiredEnvironmentValidator`·`FlywayProdSafetyValidator`·`OpenInViewSafetyValidator`·`PostgreSqlTransportSecurityValidator`·`PersistenceVendorProdSafetyValidator`·`HikariPoolConstraintValidator`. phase·종료 코드와 위반 문구는 유지(메시지 앞머리에 규칙 summary가 붙는 형태만 통일). bean이 필요한 검사(`SecretSourceValidator`, `StartupSafetyValidator`, `JpaDataSourceProfileValidator`, `JpaDangerousConfigurationGuard`)는 bean으로 유지, 부팅 전 EPP(`RuntimeEnvironmentProfileValidator`, `JpaActivationEnvironmentPostProcessor`, `TracingSamplingEnvironmentPostProcessor`, `RedisReadinessGroupPostProcessor`)는 EPP로 유지. `StartupRuleRunnerTest` 3건, 기존 검증기 테스트 전부 통과 | + +## 제거된 코드 +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +|---|---|---|---| +| SDK pub/sub 연산 표면(`RedisPubSubOperations`, `RedisShardedPubSubOperations`, `ReactiveRedisPubSubOperations`, `ReactiveRedisShardedPubSubOperations`, `PubSubChannel`, `PubSubPattern`, `ShardedPubSubChannel`, `Subscription`, `LettuceRedisPubSubOperations`, `LettuceRedisShardedPubSubOperations`, `LettuceReactiveRedisPubSubOperations`, `LettuceReactiveRedisShardedPubSubOperations`, `LiveSubscription`, `PubSubCodecs`, `PubSubOperationRequests`, `SubscriptionFlux`)과 테스트 `InMemoryRedisPubSubGateway`·`RedisPubSubOperationsContractTest` | `src/adapter/outbound/redis-sdk/src/{main,test}/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/{api/operations,api/reactive,lettuce/operations}/` | `423a29c4` | 전송(`RedisPubSubGateway`) main 구현이 없어 동작 불가(G-6b) | +| `RedisPubSubGateway`, `RedisConnectionKind.PUBSUB`, `RedisCredentialRole.PUBSUB` | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/{operations,connection}/` | `423a29c4` | 위와 같음 | +| `RedisSdkSettings.PubSub`·`Authentication.pubsubCredentialReference`, env 키 `APP_REDIS_PUBSUB_BUFFER_CAPACITY`·`APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE` | `src/adapter/outbound/redis-runtime/.../sdk/config/RedisSdkSettings.java`, `docs/registries/env-keys.yaml`, `src/.env.example` | `423a29c4` | 동작하지 않는 옵션은 키를 두지 않는다(G-4i) | +| `RedisCapability.SHARDED_PUBSUB`, `RedisOperationContext.PATTERN_SUBSCRIBE` | `src/adapter/outbound/redis-sdk/.../sdk/api/RedisCapability.java`, `.../sdk/lettuce/operations/RedisOperationContext.java` | `423a29c4` | 사용처(pub/sub 연산) 삭제 | +| `RedisCredentialRole`(enum) | `src/adapter/outbound/redis-runtime/.../sdk/lettuce/connection/RedisCredentialRole.java` | `423a29c4` | 열린 `RedisAccount` 값으로 대체 — runtime은 자기 계정 2개만 알고 SDK가 admin 계정을 기여(G-7c) | +| `RedisSdkSettings.Blocking`·`Transaction`·`Admin`과 env 키 `APP_REDIS_ADMIN_ENABLED`·`APP_REDIS_ADMIN_CREDENTIAL_REFERENCE`·`APP_REDIS_BLOCKING_MAX_CONNECTIONS`·`APP_REDIS_TRANSACTION_MAX_CONNECTIONS` | `src/adapter/outbound/redis-runtime/.../sdk/config/RedisSdkSettings.java`, `docs/registries/env-keys.yaml`, `src/.env.example` | `423a29c4` | SDK 전용 lane·계정. SDK `RedisSdkComposition` 코드 설정으로 이동(G-7c, S3-#3b) | +| `InMemoryGatewayAccess` | `src/adapter/outbound/redis-runtime/src/testFixtures/.../sdk/lettuce/operations/InMemoryGatewayAccess.java` | `423a29c4` | cache-redis 테스트는 runtime testFixtures `InMemorySemanticRedisCommands`를 직접 쓴다. semantic 스크립트 에뮬레이션은 그 fake로 이동(SDK의 `InMemoryRedisCommandGateway`에서는 제거) | +| `IdempotencyScriptsConcurrencyContractTest` | `src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/` | `423a29c4` | reflection으로 `digests` Map 구조를 고정하던 테스트. 슬롯이 `RegisteredLuaScript` final 필드가 되어 대상이 없음; 동작은 `RegisteredLuaScriptTest`가 검증 | +| `SecretSourceValidator.REDIS_ENABLED_PROPERTY`와 Redis 역할 prefix 분기(`isRedisMaterial`, `isRedisRoleSelected`, `isRedisCacheBound`, `isSelected`), `REQUIRED_PROD_SECRETS`의 Redis 8개 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java` | `423a29c4` | cache-redis `RedisProductionSecrets`가 기여(S6-#2c) | +| shared `RateLimitBounds.MAXIMUM_CLEANUP_GRACE`·`MAXIMUM_CLOCK_REGRESSION`, `EdgeRateLimitProviderNeutralContractTest.allPortableAlgorithmsHaveBoundedProviderNeutralPolicies` | `src/shared-contract/src/{main,test}/java/dev/caskeleton/shared/ratelimit/` | `423a29c4` | 정책 타입이 cache-redis로 이동(S1-#15c). 정책 검증 테스트는 이동한 `RateLimitPolicyTest`에 있음 | + +## 새로 발견한 결함 +- `P22-new-1` — `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java`: `APP_DATASOURCE_PASSWORD`를 요구할지 bootstrap이 persistence-jpa의 모듈 스위치(`ca-skeleton.persistence-jpa.enabled`)를 읽어 판정한다. S6-#2c가 Redis에 대해 없앤 것과 같은 모양(모듈 지식이 composition root에). 같은 `RequiredProductionSecrets` 기여로 옮길 수 있으나 이 묶음 범위(Redis) 밖이라 고치지 않음. +- `P22-new-2` — `infra/redis-sdk/acl/application.acl`·`all-accounts.acl`: pub/sub 표면이 사라졌는데 application 계정 ACL fixture가 여전히 `+@pubsub`와 채널 패턴 `&prod:*`를 준다(최소 권한 위반, fixture 한정). infra 파일이라 고치지 않음. +- `P22-new-3` — redis-sdk가 공개 API에 runtime 타입(`SemanticRedisCommands` 상위 인터페이스, `WritePresence`, `RedisLaneContribution`, `RedisDriverConnection`)을 노출하면서 runtime을 `implementation`으로만 의존한다. SDK를 쓰는 leaf는 README대로 runtime도 선언해야 컴파일된다(이전에도 `RedisRuntimeOwner` 때문에 같았음). `api`로 바꾸는 것은 build 변경이라 보류. diff --git a/docs/reviews/2026-09-25-review-followup-status.md b/docs/reviews/2026-09-25-review-followup-status.md index 705d91ba..afffe342 100644 --- a/docs/reviews/2026-09-25-review-followup-status.md +++ b/docs/reviews/2026-09-25-review-followup-status.md @@ -354,21 +354,21 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | G-4f | Required | `lifecycle.tls-handshake-timeout` 미적용 | 해당 없음(코드 삭제) | 같은 표 행 174 | - | - | | G-4g | Required | `pubsub.overflow-policy` 미적용 | 해당 없음(코드 삭제) | 같은 표 행 174 | - | - | | G-4h | Required | `lifecycle.acquire-timeout` 미적용 | 완료 | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java:241` → `RedisRuntimeOwner.java:153` `tryAcquire(acquireTimeout)`. 테스트 `RedisScriptLaneAdmissionTest.aCallerStillWaitingWhenTheAcquireTimeoutRunsOutIsRefusedAsNotSent`. 커밋 `6d27356e` | - | - | -| G-4i | Required | 남은 `pubsub.buffer-capacity`(+`authentication.pubsub-credential-reference`)가 버퍼를 제한하지 않음. PUBSUB lane 연결 수(`/64`)로만 쓰이고 pub/sub 전송 구현이 없음 | 남음 | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java:235-236`, `RedisSdkSettings.java:549-566`, `docs/registries/env-keys.yaml:2297`. main에 `implements RedisPubSubGateway` 0건 (= G-6b) | W3 | G-6b에서 pub/sub를 지우면 `RedisSdkSettings.PubSub`·env key `APP_REDIS_PUBSUB_BUFFER_CAPACITY`·`_PUBSUB_CREDENTIAL_REFERENCE`를 함께 삭제(AGENTS.md 완료 기준 3) | +| G-4i | Required | 남은 `pubsub.buffer-capacity`(+`authentication.pubsub-credential-reference`)가 버퍼를 제한하지 않음. PUBSUB lane 연결 수(`/64`)로만 쓰이고 pub/sub 전송 구현이 없음 | 해당 없음(코드 삭제) | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 D `1b3138cb`: `RedisSdkSettings.PubSub`·`Authentication.pubsubCredentialReference`, env 키 `APP_REDIS_PUBSUB_BUFFER_CAPACITY`·`APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE`(`docs/registries/env-keys.yaml`·`src/.env.example`) 삭제. `:app-bootstrap:verifyEnvKeys` 통과 | - | G-6b에서 pub/sub를 지우면 `RedisSdkSettings.PubSub`·env key `APP_REDIS_PUBSUB_BUFFER_CAPACITY`·`_PUBSUB_CREDENTIAL_REFERENCE`를 함께 삭제(AGENTS.md 완료 기준 3) | | G-4j | Nit | deprecated env key의 "Replaced by"가 삭제된 key를 가리킴 | 남음 | `docs/registries/env-keys.yaml:1435`(`app.redis.limits.max-batch-request-bytes`), `:1467`(`app.redis.capacity.maximum-in-flight-bytes`) | W5 | 두 행의 "Replaced by" 주석을 "대체 없음(2026-09-25 삭제)"로 수정 | | G-5a | Required | redis-runtime·redis-sdk 테스트가 cache-redis에 있어 두 leaf focused test가 빈 초록불 | 완료 | redis-sdk `src/test` 51개(`RedisSdkModuleBoundaryTest`, `LiveRedisOperationsFixture` 등), redis-runtime `src/test` 10개(`RedisRuntimeOwnerTest` 등), fake는 `src/adapter/outbound/redis-runtime/build.gradle:4,18-20` testFixtures로 공유, `src/adapter/outbound/cache-redis/build.gradle:8-17`에 redis-sdk edge 없음. 커밋 `6d27356e` | - | - | | G-5b | Required | redis-runtime leaf에 README·CLAUDE.md 없음 | 남음 | `src/adapter/outbound/redis-runtime/`에 `build.gradle`·`src`만 있음. redis-sdk는 `README.md` 추가됨. runtime 규칙은 `src/adapter/outbound/cache-redis/CLAUDE.md` "Redis runtime and optional typed SDK" 절에 섞여 있음 | W5 | `src/adapter/outbound/redis-runtime/README.md`를 만들어 제공하는 것·붙이는 방법·env 키(`app.redis.*` 소유)를 적고 cache-redis CLAUDE.md의 runtime 절을 옮김 | | G-6a | Required | SDK 진입 facade `RedisOperations`·`ReactiveRedisOperations` 구현체 0 | 해당 없음(코드 삭제) | `docs/capability-status.md` 「제거된 코드」 행 170. `implements RedisOperations\|ReactiveRedisOperations` 0건 | - | - | -| G-6b | Required | pub/sub 전송(`RedisPubSubGateway`) main 구현이 없어 SDK의 pub/sub·sharded pub/sub 연산을 쓸 수 없음 | 남음 | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubGateway.java`(인터페이스만), 구현은 test `InMemoryRedisPubSubGateway`뿐. `src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisPubSubOperations.java` 외 3개가 이 gateway에 의존. `src/adapter/outbound/redis-sdk/README.md` 표는 pub/sub를 제공한다고 적음 | W3 | D1 기준으로 redis-sdk의 `*PubSub*Operations`·`LiveSubscription`·`PubSubOperationRequests`·api pub/sub 인터페이스와 runtime `RedisPubSubGateway`·PUBSUB role/lane을 삭제하고 README 표에서 제거 | +| G-6b | Required | pub/sub 전송(`RedisPubSubGateway`) main 구현이 없어 SDK의 pub/sub·sharded pub/sub 연산을 쓸 수 없음 | 해당 없음(코드 삭제) | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 D `1b3138cb`. **구현 대신 삭제를 택함**: 구현하려면 Lettuce pub/sub 연결 수명·버퍼 한도·재구독·sharded 라우팅·실제 벤더 lane을 새로 만들어야 하고(capability 규칙 3 "켜면 완전히 동작"), main 소비자가 0이다. 삭제는 SDK 파일 18개와 runtime 인터페이스 1개로 끝난다. 카탈로그 `redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml:745-780`의 PUBLISH/SUBSCRIBE/PSUBSCRIBE/SPUBLISH… 8개는 `BLOCKED`(카탈로그는 서버의 모든 명령을 판정해야 하므로 행은 남김), `RedisCapability.SHARDED_PUBSUB`·`pattern-subscribe` permit 정책 삭제, `redis-sdk/README.md` 표에서 pub/sub 제거 | - | D1 기준으로 redis-sdk의 `*PubSub*Operations`·`LiveSubscription`·`PubSubOperationRequests`·api pub/sub 인터페이스와 runtime `RedisPubSubGateway`·PUBSUB role/lane을 삭제하고 README 표에서 제거 | | G-6c | Required | redis-sdk `RedisConnectionRegistry`가 호출자 0이고 `RedisRuntimeOwner` lane 한도 로직과 중복 | 해당 없음(코드 삭제) | 「제거된 코드」 행 173 | - | - | | G-6d | Required | cache-redis realtime adapter(`RedisEphemeralFanoutAdapter`, `RedisConnectionRegistryAdapter`) 조립처 없음 | 해당 없음(코드 삭제) | 「제거된 코드」 행 156, 210. cache-redis main에 `realtime/` 패키지 없음 | - | - | | G-6e | Required | SDK를 도입할 조립 코드·경로가 없음 | 완료 | `src/adapter/outbound/redis-sdk/README.md` "Adding it"(서비스 어댑터 leaf에서 `implementation` + `modules.json` edge, AGENTS.md 라이브러리형 예외), per-structure `Lettuce*Operations` 구현 36개, 조립 예시 `LiveRedisOperationsFixture`(test). 커밋 `6d27356e` | - | - | -| G-7a | Consider | runtime `RedisCommandGateway`가 SDK 표면 전체(약 118개 메서드)를 들고 있는데 cache-redis·health는 4개만 씀 | 남음 | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java`(1227줄), `LettuceRedisCommandGateway.java`(1282줄). cache-redis main이 쓰는 것: `loadScript`·`evaluateRegisteredForList`·`evaluateRegisteredForLong`, health는 `ping` | W3 | runtime에는 이 4개만 가진 좁은 gateway를 두고 나머지 메서드와 `api.command`(RAW_ONLY 등)는 redis-sdk 소유 gateway로 이동 | +| G-7a | Consider | runtime `RedisCommandGateway`가 SDK 표면 전체(약 118개 메서드)를 들고 있는데 cache-redis·health는 4개만 씀 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`. runtime 계약은 `redis-runtime/.../runtime/command/SemanticRedisCommands.java:19`(get·set(Duration)·getAndDelete·incrementBy·ping·loadScript·evaluateRegisteredForList/Long 8개)와 구현 `LettuceSemanticRedisCommands`. 118개 메서드 `RedisCommandGateway`와 `LettuceRedisCommandGateway`는 redis-sdk로 이동해 `redis-sdk/.../sdk/lettuce/operations/RedisCommandGateway.java:48`에서 `SemanticRedisCommands`를 확장하고, 빌린 연결의 `RedisLease.driver()`로 `LettuceRedisCommandGateway.over(...)`를 만든다. `api.command`·`api.error`·`api.operations`·`RedisVersion`·페이지 타입도 SDK로. cache-redis·health는 8개만 사용 | - | runtime에는 이 4개만 가진 좁은 gateway를 두고 나머지 메서드와 `api.command`(RAW_ONLY 등)는 redis-sdk 소유 gateway로 이동 | | G-7b | Consider | raw 자격 증명·raw allowlist가 runtime에 있음 | 해당 없음(코드 삭제) | 「제거된 코드」 행 174(`raw.*`, `RedisCredentialRole.RAW`). `RedisCredentialRole.java:23-29`에 RAW 없음 | - | - | -| G-7c | Consider | SDK 전용 admin 자격 증명·ADMIN lane이 runtime에 있음 | 남음 | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java:143-148,237`. 사용처는 redis-sdk `LettuceRedisAdminOperations`뿐 | W3 | G-7a 분리 때 admin 자격 증명 해석과 ADMIN lane 한도를 redis-sdk 쪽 조립으로 이동 | -| G-7d | Consider | runtime과 sdk가 같은 패키지 `…cache.redis.sdk.*`를 공유 | 남음 | redis-runtime main 전 파일이 `dev.caskeleton.adapter.outbound.cache.redis.sdk.*`(예: `.../sdk/lettuce/connection/RedisRuntimeOwner.java:1`) | W3 | redis-runtime 패키지를 `dev.caskeleton.adapter.outbound.cache.redis.runtime.*`로 이동 | -| G-7e | Consider | runtime `RedisCorrectnessRoles`가 소비자 selector 값(session·idempotency·rate-limit·lease)을 하드코딩 | 남음 | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCorrectnessRoles.java:32-37` | W3 | selector 목록을 소비자인 cache-redis(`RedisCapabilitySettings`)로 옮기고 runtime은 "required 여부"만 받도록 변경 | -| G-8 | Consider | EVALSHA+NOSCRIPT 재로드 헬퍼가 4벌 복사, `CacheScripts`만 메시지 `startsWith("NOSCRIPT")` 폴백 | 남음 | `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/cache/CacheScripts.java:41-87`, `ratelimit/RateLimitScripts.java:209-263`, `lease/LeaseScripts.java:106-160`, `idempotency/IdempotencyScripts.java:213-271` | W3 | cache-redis에 `RegisteredLuaScript`(digest 캐시·NOSCRIPT 판별·재로드 1회) 하나를 두고 네 클래스가 사용 | +| G-7c | Consider | SDK 전용 admin 자격 증명·ADMIN lane이 runtime에 있음 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`. runtime lane은 `RedisConnectionKind.java:12-16` REGULAR·SCRIPT만. BLOCKING·TRANSACTION·ADMIN은 `redis-sdk/.../sdk/lettuce/connection/RedisSdkLane.java:19`, admin 계정과 lane 한도는 `RedisSdkComposition.java`(서비스가 `RedisLaneContribution`·`RedisAccountContribution` 빈으로 기여, runtime `RedisRuntimeAutoConfiguration`이 모아 풀·자격 증명을 만든다). `app.redis.admin.*`·`app.redis.blocking.max-connections`·`app.redis.transaction.max-connections` 설정과 env 키 4개 삭제 — SDK의 다른 설정처럼 코드 설정(README "configuration that is code")으로. 테스트 `RedisRuntimeAutoConfigurationTest.configuredAccountsAreResolvedPerRole`(기여 계정 해석)·`aLaneAnotherModuleContributesIsPooledByTheOwner`·`aLaneComposedTwiceFailsTheContext` | - | G-7a 분리 때 admin 자격 증명 해석과 ADMIN lane 한도를 redis-sdk 쪽 조립으로 이동 | +| G-7d | Consider | runtime과 sdk가 같은 패키지 `…cache.redis.sdk.*`를 공유 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`. redis-runtime 전 파일이 `dev.caskeleton.adapter.outbound.cache.redis.runtime.*`(`RedisDeploymentMode`, `key`, `cluster`, `command`, `connection`, `config`). split package 해소. `RedisRuntimePackageBoundaryTest.noRuntimeSourceReferencesTheTypedSdkPackage`. SDK 쪽 `RedisSdkModuleBoundaryTest`는 SDK root만 스캔 | - | redis-runtime 패키지를 `dev.caskeleton.adapter.outbound.cache.redis.runtime.*`로 이동 | +| G-7e | Consider | runtime `RedisCorrectnessRoles`가 소비자 selector 값(session·idempotency·rate-limit·lease)을 하드코딩 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`. selector 표는 `cache-redis/.../capability/RedisCorrectnessRoleSelectors.java:48`(W2에서 역할별 secret까지 한 표로)로 옮기고 cache-redis `META-INF/spring.factories`에 `RedisCorrectnessRequirement`로 등록. runtime `RedisCorrectnessRoles.java:44`는 등록된 요구에 "required 여부"만 묻는다. `RedisRuntimeAutoConfigurationTest.withoutARequirementTheRuntimeCreatesNoRequiredContributor`(runtime은 selector를 모른다)·`aModuleThatNeedsRedisForCorrectnessGetsTheRequiredContributor`, `RedisReadinessGroupPostProcessorTest.eachCorrectnessSelectorAppendsRedisReadiness`, live `LiveRedisCompositionTest` 스크립트 role 2건 통과 | - | selector 목록을 소비자인 cache-redis(`RedisCapabilitySettings`)로 옮기고 runtime은 "required 여부"만 받도록 변경 | +| G-8 | Consider | EVALSHA+NOSCRIPT 재로드 헬퍼가 4벌 복사, `CacheScripts`만 메시지 `startsWith("NOSCRIPT")` 폴백 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`: `cache-redis/.../RegisteredLuaScript.java:29`(digest 캐시·NOSCRIPT 판별 `:114`·재로드 1회·응답 디코딩)을 Cache/RateLimit/Lease/IdempotencyScripts 4곳이 사용. `LeaseScriptsTest.aProgramTheServerForgotIsReloadedEvenWhenOnlyTheMessageSaysNoScript` FAIL(`CompletionException` caused by `RedisCommandExecutionException` — 메시지로만 온 NOSCRIPT를 lease가 재로드하지 않음)→PASS. `RegisteredLuaScriptTest` 4건 | - | cache-redis에 `RegisteredLuaScript`(digest 캐시·NOSCRIPT 판별·재로드 1회) 하나를 두고 네 클래스가 사용 | | G-9a | Consider | 장애 WARN이 capability·operation·type 조합마다 JVM 수명 동안 한 번뿐(`WARNED` 비우지 않음) | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisSemanticFailureLogger.java:28,58`: once-per-JVM `Set` → key별 마지막 WARN 시각 맵, `WARN_INTERVAL`(1분)마다 다시 WARN. 테스트용 package-private `report(..., nowNanos)`. `RedisSemanticFailureLoggerTest.aContinuingFailureWarnsAgainOnceTheWindowHasPassed` FAIL(`Expected size: 2 but was: 1`)→PASS | - | `WARNED`를 key별 마지막 WARN 시각 맵으로 바꿔 시간 창(예: 1분)마다 다시 WARN | | G-9b | Consider | `failureType`이 대부분 wrapper(`ExecutionException`) 이름 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisSemanticFailureLogger.java:39`: `ExecutionException`/`CompletionException` cause를 풀어 기록. `aWrappedFailureIsReportedByItsCause` FAIL(`expected "IllegalStateException" but was "ExecutionException"`)→PASS | - | `report()`에서 `ExecutionException`·`CompletionException` cause를 풀고 기록 | | G-10a | Consider | SCRIPT ACL probe가 `return {1}`이라 스크립트 내부 명령(`TIME`/`HSET`/`PEXPIRE`/`DEL`) 권한 부족을 기동 때 못 잡음 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisSemanticScriptAclProbe.java:29-38`: probe key에서 `TIME`→`HSET`→`PEXPIRE`→`HGET`→`DEL`을 실행하고 읽은 값이 쓴 값과 같을 때만 `{1}`. `anAccountDeniedACommandTheScriptsCallFailsStartup`[HSET/PEXPIRE/HGET/DEL] FAIL→PASS. 실제 Redis standalone·cluster에서 `LiveRedisSemanticScriptAclProbeTest` 2건 PASS. 테스트 ACL `+time`은 NEW-5a(W1)에서 추가 | - | probe 스크립트를 probeKey에 `TIME`·`HSET`·`PEXPIRE`·`HGET`·`DEL`을 실제 실행하는 것으로 교체하고, 테스트 ACL에 `+time` 추가 | @@ -686,7 +686,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | X1-지도-요청 멱등성 | 권고 | 계약 2개·store 3개·executor 조립 3곳·inbound ledger 3개 → V2 정본, 조립 1곳 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 조립이 한 곳이다(`composition:idempotency`). 두 root가 같은 모듈을 쓴다. | - | X1-#2b대로 `composition:idempotency` 신설 후 두 곳을 모듈 하나로 | | X1-지도-자연키 생성-또는-반환 | 권고 | durable operation을 notification 방식(`ON CONFLICT`)으로, upsert executor 삭제 (= E-2) | 완료 | `DurableOperationJpaRepository.java:48` `ON CONFLICT … DO NOTHING`, `DurableOperationStoreAdapter.java:46-58` 삽입 후 재조회, upsert 실행기 7종 삭제(`docs/capability-status.md:158`), 커밋 `6d27356e` | - | - | | X1-지도-Inbox / 소비자 dedup | 권고 | app-core inbox 삭제, 나머지(messaging inbox·notification ledger) 유지 | 완료 | `application/inbox/`·`PostgreSqlSameStoreInboxAdapter` 삭제(`docs/capability-status.md:155`), mongo change stream dedup 삭제(`:151`); application-core 패키지 목록에 `inbox` 없음, 커밋 `6d27356e` | - | - | -| X1-지도-lock / lease / fencing | 권고 | 미사용 포트·claim executor 삭제, fencing은 contract kit로 | 남음 | claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog` 삭제(`docs/capability-status.md:152-153,157`). 남은 포트 2개 모두 비즈니스 소비자 0: `DistributedLockPort`(참조는 `StartupSafetyValidator.java:51` 존재 검사뿐), `DistributedLeasePort`(참조 0) | W3 | 결정(2026-09-25): lock·lease 유지, 쓰지 않는 claim executor만 삭제, fencing은 계약 테스트로 | +| X1-지도-lock / lease / fencing | 권고 | 미사용 포트·claim executor 삭제, fencing은 contract kit로 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): 소유자 결정 8대로 lock·lease 포트 유지. claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog`는 이미 `208077fd`에서 삭제돼 남은 미사용 포트 없음. fencing은 contract kit로(P22 W2 `7f39bfda`): `application-core/src/testFixtures/.../lease/testkit/DistributedLeaseContract.java`(밀려난 holder의 renew·release는 NotOwner이고 후임의 lease를 건드리지 않는다, 같은 attempt 재acquire는 replay, 이중 release는 AlreadyAbsent — 7건)를 fake `InMemoryDistributedLease`(`InMemoryDistributedLeaseContractTest`), Redis 어댑터+in-memory 명령(`RedisDistributedLeaseContractTest`), 실제 Redis(`LiveRedisDistributedLeaseContractTest`, standalone lane)가 모두 통과. lock 포트의 공통 계약(JDBC 어댑터 포함)은 Wave 4 범위로 남김 | - | 결정(2026-09-25): lock·lease 유지, 쓰지 않는 claim executor만 삭제, fencing은 계약 테스트로 | | X1-지도-caller 트랜잭션 guard | 권고 | 9벌 복사 → persistence-jpa helper 1개 (= E-3) | 남음 | persistence-jpa 복사본 4벌 + guard 없는 곳 10개(세부 X1-#4) | W3 | X1-#4 | | X1-지도-Backoff 계산식 | 권고 | 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 남음 | 앱 쪽 3개 남음(`OutboxBackoffPolicy.java:63-68`, `ExponentialFullJitterBackoff.java:78`, `RetryBackoff.java:42`), JPA 2개 삭제 | W3 | X1-#9 | | X1-지도-Rate limit | 권고 | web 전용 병렬 타입 세트 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·web `RateLimitDecision`·`RateLimitFailurePolicy`·`WebMvcThrottleFilter` 삭제(`docs/capability-status.md:99`); 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitTransportBridge` → shared `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - | @@ -792,7 +792,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#14 | Consider | notification platform 미사용 약 920줄(예외 12, security 3, sms/push/email/webpush) (= B-8) | 해당 없음(코드 삭제) | 「제거된 코드」 notification `sms`·`push`·`email`·`webpush` facade, throw 0 예외 12종, redaction 5종 행. 해당 디렉터리 없음 확인 | - | - | | S1-#15a | Consider | shared-contract `activation/*`(bootstrap만 사용) | 해당 없음(코드 삭제) | 「제거된 코드」 `MasterSwitch`·`MasterSwitchParser`(shared-contract `activation` 전체) 행 | - | - | | S1-#15b | Consider | shared-contract `opstore/*` 구현·소비자 0 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`(X1-#6f와 같은 삭제) | - | `opstore` 패키지 삭제 | -| S1-#15c | Consider | ratelimit 정책 타입이 cache-redis 전용 | 남음 | `shared-contract/.../ratelimit/RateLimitPolicy`·`RateLimitAlgorithm` main 소비자는 cache-redis뿐, `RateLimitEvaluationDedupPolicy`는 테스트만 참조 | W3 | 세 타입을 `adapter:outbound:cache-redis`로 이동(`EdgeRateLimitPort` 계열만 shared에 유지) | +| S1-#15c | Consider | ratelimit 정책 타입이 cache-redis 전용 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W2 `7f39bfda`: `RateLimitPolicy`·`RateLimitAlgorithm`·`RateLimitEvaluationDedupPolicy`(+ 이들만 쓰는 `RateLimitFailurePolicy`)와 테스트 2개를 `cache-redis/.../ratelimit/`로 이동, 정책 검증 bounds는 `RateLimitPolicyBounds`(package-private). shared에는 `EdgeRateLimitPort`·`RateLimitRequest`·`RateLimitOutcome`·`RateLimitDecision`·`RateParameters`·subject 계열만 남음. `:shared-contract:check`·`:adapter:inbound:web:check` 통과 | - | 세 타입을 `adapter:outbound:cache-redis`로 이동(`EdgeRateLimitPort` 계열만 shared에 유지) | | S1-#15d | Consider | shared-contract CLAUDE.md 책임 목록이 패키지 일부만 설명 | 남음 | `shared-contract/CLAUDE.md:17-30`은 response·error·request·health·tracing만, 실제 패키지 15개(annotation·concurrency·headers·metrics·operation·registry·runtime·security·ratelimit·opstore 누락) | W5 | 책임 목록을 현재 패키지 기준으로 갱신 | | S1-#16 | Consider | 문서가 말하는 `application-core → domain-core` 의존이 빌드에 없음 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): `src/application-core/build.gradle` `implementation project(':domain-core')` 복원(registry 허용 edge). `architectureCheck` PASS. 같은 행의 `NotificationIdGeneratorPort`·`UploadIdentifierFactory` → `IdFactory` 정리는 application-notification/fileserver·persistence-jpa·composition을 바꾸는 작업이라 하지 않음(P16-new-5) | - | `application-core/build.gradle`에 `implementation project(':domain-core')` 복원, `NotificationIdGeneratorPort`·`UploadIdentifierFactory`를 `IdFactory` 기반으로 정리 | | S1-#17a | Consider | objectstorage 식별자 클래스 6개·가드 2개 복사 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `7a21c6e7`. `ObjectId`·`ObjectReference`·`ObjectStageHandle`·`ObjectVersionToken`을 compact constructor + `toString`(redacted) record로(`identity/ObjectId.java:4`). `DirectTransferSessionId`·`PartReceiptToken`은 D-7a에서 이미 삭제. 가드는 `ObjectModelSupport.requireBoundedToken`(`model/ObjectModelSupport.java:9`) 하나, `ObjectRequestSupport.boundedToken` 삭제. `:application-objectstorage:check`, control record 골든 digest(`ObjectControlRecordCodecTest`) PASS | - | 식별자를 record + `toString` 재정의로, 가드는 하나로 | @@ -839,16 +839,16 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S3-#1 | Required | httpclient blocking/reactive 병렬 스택이 이미 갈라짐 (= H-5, H-7) | 완료 | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D 커밋 `06764fcb`에서 reactive 스택(WebClient·Reactor Netty)과 webflux·reactor·reactor-netty·reactor-test·blockhound 의존 삭제. blocking(RestClient) 경로 하나만 남음. `clients[N].api` 설정 키·`ClientApiType`·`TransportType.REACTOR_NETTY` 삭제, env-fields.yaml 행 삭제, lockfile 재생성(httpclient·app-bootstrap). Jetty HTTP/3 실험 transport는 reactive SPI에 묶여 있어 blocking SPI(`JettyClientHttpRequestFactory`)로 옮김(자동 조립 안 됨은 그대로) `HC/http3/JettyHttp3TransportProvider.java:49` | - | 결정(2026-09-25): D4를 outbound에도 적용 — httpclient reactive(WebClient·Reactor Netty) 스택과 webflux·reactor 의존 삭제 | | S3-#2a | Required | reactive streaming 요청이 admission·deadline·credential 없이 나감 | 해당 없음(코드 삭제) | Wave 1–2 P11 (fcddab7e·Wave 2 커밋): D `06764fcb`에서 `webclient/ReactiveStreamingGateway` 삭제. blocking 스트리밍은 deadline·credential·admission 적용 `HC/restclient/BlockingStreamingGateway.java:69,82,106` | - | S3-#1에서 reactive를 지우면 함께 삭제, 유지하면 blocking과 같은 credential·admission·deadline 단계 적용 + 동작 테스트 | | S3-#2b | Required | 진입점 6개가 호출 파이프라인을 각자 조립 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `CallSetup.prepare(lease, operation)`이 blocking runtime·metadata·target policy·deadline(+guard)을 준비하고 `admit()`·`credentials()`·`credentialRequest()` 제공(`HC/restclient/CallSetup.java:49,79`). generic(`DefaultGenericHttpGateway.java:69`)과 streaming(`BlockingStreamingGateway.java:50`) 진입점이 사용. Dynamic Target은 target 준비(SSRF 핀)가 달라 `CallSetup.guardedDeadline`과 admission permit만 공유(`dynamic/DefaultDynamicTargetGateway.java:104`) — 이 과정에서 P26-new-1 발견·수정. reactive 진입점 3개는 결정 9로 이미 삭제. service(H1)는 generic gateway를 경유 | - | `CallSetup.prepare(lease, operation)`이 metadata/prepared/deadline/admission/credentials 반환, 진입점은 전송만 다르게 | -| S3-#3a | Required | 118개 메서드 `RedisCommandGateway`, runtime이 SDK 개념에 역의존 (= G-7) | 남음 | `redis-runtime/.../lettuce/operations/RedisCommandGateway.java`(1,227줄, 메서드 118), `:1107-1134` `sendApprovedRaw/sendAdminDiagnostic/sendExtension`, `lettuce/connection/RedisConnectionKind.java:25-33` BLOCKING·TRANSACTION·PUBSUB lane, `:64` `forCommand(RedisCommandDescriptor)` | W3 | runtime 계약은 semantic adapter가 쓰는 8개(`SemanticRedisCommands`)로, 나머지는 redis-sdk 확장 인터페이스로 이동(redis-sdk 유지 결정 반영), lane은 REGULAR·SCRIPT만 | -| S3-#3b | Required | runtime이 `Sdk` 이름·`...redis.sdk` 패키지를 쓰고 redis-sdk와 split package | 남음 | `redis-runtime/.../sdk/config/RedisSdkSettings.java`(670줄), `RedisSdkAutoConfiguration.java`, redis-runtime·redis-sdk 공유 패키지 9개 | W3 | `RedisRuntimeSettings`로 개명, runtime 패키지를 `...redis.runtime.*`로, SDK 전용 설정 섹션은 redis-sdk로 | +| S3-#3a | Required | 118개 메서드 `RedisCommandGateway`, runtime이 SDK 개념에 역의존 (= G-7) | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): = G-7a·G-7c. runtime 계약 8개, 나머지는 SDK 확장 인터페이스, lane은 REGULAR·SCRIPT, `forCommand(RedisCommandDescriptor)`는 SDK `RedisSdkLane.forCommand`로 | - | runtime 계약은 semantic adapter가 쓰는 8개(`SemanticRedisCommands`)로, 나머지는 redis-sdk 확장 인터페이스로 이동(redis-sdk 유지 결정 반영), lane은 REGULAR·SCRIPT만 | +| S3-#3b | Required | runtime이 `Sdk` 이름·`...redis.sdk` 패키지를 쓰고 redis-sdk와 split package | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): = G-7d. `RedisSdkSettings`→`RedisRuntimeSettings`, `RedisSdkAutoConfiguration`→`RedisRuntimeAutoConfiguration`, SDK 전용 섹션(blocking·transaction·admin)은 runtime 설정에서 빠지고 SDK 코드 설정으로. `RedisRuntimePackageBoundaryTest.noRuntimeTypeIsNamedAfterTheSdk` | - | `RedisRuntimeSettings`로 개명, runtime 패키지를 `...redis.runtime.*`로, SDK 전용 설정 섹션은 redis-sdk로 | | S3-#4a | Required | cache-redis에서 "안 보냄/보냈는지 모름" 구분을 rate-limit만 함 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): 멱등성·lease는 NEW-5c 수정. cache는 현황표 근거("lane 거절도 Indeterminate")가 사실과 다름: cache는 이미 lane 거절을 `DEGRADED_UNAVAILABLE`(=안 보냄)로 돌려준다. 빠진 쪽은 반대 방향이었다 — 보낸 뒤 응답을 잃은 쓰기도 `DEGRADED_UNAVAILABLE`였다. `RedisCacheRegionAdapter.java:241,294,314,328`에 `sent` 플래그를 두어 쓰기 명령을 보낸 뒤의 실패는 `INDETERMINATE`, 그 전(lane 거절·연결·generation 조회)은 `DEGRADED_UNAVAILABLE`. 테스트 `RedisCacheRegionAdapterTest.aWriteWhoseReplyWasLostIsIndeterminate`/`anInvalidationWhoseReplyWasLostIsIndeterminate`/`aRegionInvalidationWhoseReplyWasLostIsIndeterminate` FAIL(`expected: INDETERMINATE but was: DEGRADED_UNAVAILABLE`)→PASS, 가드 `aWriteThatFailedBeforeItsSetWasSentDegrades` PASS | - | 멱등성·lease·cache의 실패 분류에 `metadata().ambiguousExecution()`로 NOT_SENT/AMBIGUOUS 구분 추가 | -| S3-#4b | Required | "lease 빌림 → `.get(timeout)` → 예외 처리" 틀 복사, Lua 응답 디코더 3벌 | 남음 | `catch (InterruptedException` 16곳(멱등성 6·lease 4·cache 4·rate-limit 1·probe 1), 디코더 `idempotency/IdempotencyScripts.java:273`, `lease/LeaseScripts.java:162`, `ratelimit/RateLimitScripts.java:280` | W3 | `SemanticRedisCall.run(...)` 공통 틀 + 응답 디코딩을 등록 스크립트 쪽 한 곳으로 | -| S3-#5 | Consider | `RedisIdempotencyStoreAdapter.transition` 인자 14~15개, 상태 문자열 switch 반복 | 남음 | `cache-redis/.../idempotency/RedisIdempotencyStoreAdapter.java:164-180`(`transition` 호출 14개 인자), `:137-157` 등 문자열 switch | W3 | `IdempotencyScripts.Reply`에서 `enum ScriptStatus`로 한 번 파싱, 호출부는 `Map` | +| S3-#4b | Required | "lease 빌림 → `.get(timeout)` → 예외 처리" 틀 복사, Lua 응답 디코더 3벌 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`: `cache-redis/.../SemanticRedisCall.java:35` — 빌림·bounded wait·not-sent/unknown 판정 한 곳(`effect`: 스크립트, `run`+`markSent`: cache). 네 어댑터의 `catch (InterruptedException` 15곳이 사라지고 cache-redis main에는 `SemanticRedisCall`과 시작 probe만 남음. Lua 응답 디코딩은 `RegisteredLuaScript.number/text/requireShape`. 기존 어댑터 테스트(`RedisIdempotencyStoreAdapterTest`·`RedisDistributedLeaseAdapterTest`·`RedisEdgeRateLimitAdapterTest`·`RedisCacheRegionAdapterTest`)와 live `LiveRedisSemanticPortsTest` 10건 통과 | - | `SemanticRedisCall.run(...)` 공통 틀 + 응답 디코딩을 등록 스크립트 쪽 한 곳으로 | +| S3-#5 | Consider | `RedisIdempotencyStoreAdapter.transition` 인자 14~15개, 상태 문자열 switch 반복 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`: `IdempotencyScripts.ScriptStatus`(`IdempotencyScripts.java:228`)로 한 번 파싱, switch는 enum, `transition(...)`은 `Transition` record + `Map`(`RedisIdempotencyStoreAdapter.java:428`) — 인자 16개→7개 | - | `IdempotencyScripts.Reply`에서 `enum ScriptStatus`로 한 번 파싱, 호출부는 `Map` | | S3-#6 | Consider | 대체 불가능한 확장 지점(`HttpClientTagPolicy` bean) | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `HttpClientObservationAutoConfiguration`의 `HttpClientTagPolicy` bean 삭제(소비처 0, private 생성자라 override 불가). `BlockingExecutionSupport` → `ExecutionSupport` 개명(`HC/restclient/ExecutionSupport.java`, bean `httpClientExecutionSupport` `HttpClientObservationAutoConfiguration.java:24`). 커밋 `93251e76` | - | bean 삭제, `BlockingExecutionSupport`는 `ExecutionSupport`로 개명 | | S3-#7 | Consider | 구현 1개짜리 인터페이스 4개 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): 삭제: `RetryCoordinator` 인터페이스(구현 `BlockingRetryCoordinator`를 `RetryCoordinator`로 개명, `HC/resilience/RetryCoordinator.java:20`, 테스트 `RetryCoordinatorTest`), `ExecutionEvidenceClassifier` 인터페이스(`DefaultExecutionEvidenceClassifier`를 그 이름으로, `HC/resilience/ExecutionEvidenceClassifier.java:12`). 유지(근거): `RetryEligibilityEngine` — `DefaultGenericHttpGatewayTest:287,311`이 lambda fake를 넣고 `TestGateways.forProfile(.., RetryEligibilityEngine)`이 교체 지점; `BackoffStrategy` — `RetryCoordinatorTest.ambiguousOutcomeIsRaisedRatherThanRetried`·`exhaustedBudgetStopsRetryingImmediately`가 `(a, r, d) -> Duration.ZERO` fake를 씀(삭제 시도 시 컴파일 실패로 확인) | - | 인터페이스 삭제, 구현체를 인터페이스 이름으로 개명 | | S3-#8a | Consider | `BoundedErrorBody`·`spring7/*`·`migration/*` 도달 불가 | 해당 없음(코드 삭제) | 「제거된 코드」 httpclient `BoundedErrorBody`, Spring 7 service group·`RestTemplate` 이행 패키지 행 | - | - | | S3-#8b | Consider | `MultipartReplayability`·`SafeHttpLogEvent`는 테스트만 참조 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `SafeHttpLogEvent`와 전용 테스트 메서드 `HttpClientTagPolicyTest.safeLogEventCarriesNoSecretOrExpandedUrl` 삭제. `MultipartReplayability`는 결정 9 reactive 삭제(`6d27356e` 이전 커밋)로 이미 없음. http3 유지 | - | 두 클래스와 전용 테스트 삭제(http3는 유지) | -| S3-#9 | Consider | `RedisTopologyClientFactory` 662줄 역할 과다 | 남음 | `redis-runtime/.../lettuce/connection/RedisTopologyClientFactory.java` 662줄(변화 없음) | W3 | `RuntimeClient` 구현 3개·`SharedClientResources`를 package-private top-level 클래스로 이동 | +| S3-#9 | Consider | `RedisTopologyClientFactory` 662줄 역할 과다 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W1 `bd0e0bc6`: `RedisTopologyClientFactory` 662→371줄. `StandaloneRuntimeClient`·`ClusterRuntimeClient`·`AccountRoutingRuntimeClient`·`SharedClientResources`·`LaneConnection`·`ShutdownBudget`를 package-private top-level로 | - | `RuntimeClient` 구현 3개·`SharedClientResources`를 package-private top-level 클래스로 이동 | | S3-#10 | Consider | settings → profile 필드 단위 복사, `valueOf(toUpperCase())` 반복 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `HttpClientPlatformSettings`의 enum 필드 7개(`mode`·`transport`·`protocols`·`authentication.type`·`retry.jitter`·`retry.retryAfter`·`proxy.type`)를 enum 타입으로 선언(`HC/autoconfigure/HttpClientPlatformSettings.java:127,131,134,212,225,226,255`), binder가 대소문자 변환. `HttpClientProfileFactory`의 `valueOf(toUpperCase())` 7곳 삭제, 복사 구조 유지. 동작 보존 리팩터라 새 FAIL 테스트 없음 — 기존 `HttpClientPlatformEnvManifestTest`·`UnsafeStartupConfigurationTest`(`SIMPLE`·`HTTP_3`)·`HttpClientPlatformActivationTest.detailSettingsAreNotBoundWhileTheCapabilityIsOff`(`NOT_A_TRANSPORT`) 통과. prefix·strict 바인딩(3-B, S3-lead-2)은 건드리지 않음 | - | settings 필드를 enum 타입으로 선언(binder가 대소문자 변환), 복사 구조는 유지 | | S3-#11 | Nit | 이력 서술 주석·inline FQN | 남음 | 재측정 "used to/no longer": httpclient 27·redis-runtime 6·redis-sdk 9·cache-redis 7줄, `cache-redis/.../capability/RedisCapabilityConfig.java:30-32` "376 lines … (BOOT-007)", httpclient inline FQN 약 91줄 | W5 | 불변 조건만 남기고 이력은 git/ADR로, FQN은 import로(`HttpMethod`/`HttpStatus` 충돌만 예외) | | S3-#12a | Nit | `CacheKeys`가 가변 generation 상태 보유, `KeyDigest`가 설정 패키지에 | 남음 | `cache-redis/.../cache/RedisCacheRegionAdapter.java:375,430`(`CacheKeys.observeGeneration`), `capability/RedisKeys.java:37` `KeyDigest` | W5 | `RegionGeneration` 분리, `KeyDigest`를 keyspace 패키지로 옮기고 `RedisNamespace.prefix()` 사용 | @@ -964,9 +964,9 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S6-#1c | Required | 조립되지 않는 websocket 플랫폼 라이브러리 약 9.7k줄 | 완료 | main 12,954 → 1,557줄(`stomp/` 491, `servlet`·`outbound`·`budget`·`core`·`protocol` 1,066). 나머지 패키지 삭제(`CS:185,187`). 남긴 라이브러리는 Wave 3 결정대로 README에 라이브러리 API로 명시(`src/adapter/inbound/websocket/README.md:6-13,56`), `6d27356e` | - | - | | S6-#2a | Required | capability 의존 규칙이 6곳(CDV, DSR, `RedisActivationValidator`, ORBRV, `MasterSwitch`, endpoint)에 흩어짐 (= L-6) | 해당 없음(코드 삭제) | `CS:237`(DSR), `CS:241`(ORBRV), `CS:248`(`MasterSwitch`), `CS:249`(CDV·endpoint), `CS:252`(RAV). capability 의존은 build 줄로 표현(`src/app-bootstrap/build.gradle:139-153`) | - | - | | S6-#2b | Required | `ca-skeleton.outbox.relay-enabled` 없을 때 기본값 해석이 여전히 갈림 | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): 기본값 불일치만 수정(조립 위치 이동은 X1-#1i, Wave 3 3-C). `OutboxSettingsTest.bindsAllSixDefaultsWhenFieldsAreNull` FAIL("Expecting value to be false but was true") → PASS, `OutboxConfigTest.withoutTheRelayKeyTheRelaySchedulerIsNotAssembled` FAIL(scheduler 조립됨) → PASS. `matchIfMissing` 삭제(`src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java:69`), null 기본값 false(`OutboxSettings.java:37`), `src/app-bootstrap/README.md` 문구 | - | relay 조립을 `composition:*` 모듈로 옮길 때(소유자 결정) 기본값을 `false` 하나로: `matchIfMissing` 삭제, `OutboxSettings` null 기본값을 `false`로 | -| S6-#2c | Required | Redis 역할 표 2벌, bootstrap이 Redis 역할별 prod secret 규칙을 앎 | 남음 | `RedisCorrectnessRoles.java:32-37`(redis-runtime) vs `BS/runtime/SecretSourceValidator.java:137-158`(prefix 분기) + 모듈 키 사본 `REDIS_ENABLED_PROPERTY`(`:31`), secret 목록 `:38-48` | W3 | Redis secret 요구 판정을 cache-redis 모듈로 옮기고 `RedisCorrectnessRoles` 표에서 파생; `SecretSourceValidator`는 모듈이 기여한 필요 secret 목록만 검사 | +| S6-#2c | Required | Redis 역할 표 2벌, bootstrap이 Redis 역할별 prod secret 규칙을 앎 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W2 `7f39bfda`: Redis 역할별 secret 판정은 `cache-redis/.../capability/RedisProductionSecrets.java`가 `RedisCorrectnessRoleSelectors.ROLES`(역할·selector·required·scripted·secret 한 표)에서 파생해 `support.startup.RequiredProductionSecrets` 빈으로 기여(Redis가 켜졌을 때만 존재). `SecretSourceValidator`는 `REQUIRED_PROD_SECRETS`(datasource·pseudonymization salt) + 모듈 기여 목록만 검사하고 `REDIS_ENABLED_PROPERTY`·역할 prefix 분기 삭제. 레지스트리 `secrets-classification.yaml`의 Redis secret 8행에 `required_when`. 테스트 `RedisProductionSecretsTest`(역할별 5 + 비선택 2), `SecretSourceValidatorTest.aSecretAModuleContributedIsRequiredInProd` 외 2건, `SecretsClassificationRegistryTest` 통과 | - | Redis secret 요구 판정을 cache-redis 모듈로 옮기고 `RedisCorrectnessRoles` 표에서 파생; `SecretSourceValidator`는 모듈이 기여한 필요 secret 목록만 검사 | | S6-#2d | Required | `capabilities.idempotency.provider` 기본값이 `disabled`/`jdbc`로 갈림 | 완료 | 모두 `disabled`: `BS/runtime/SecretSourceValidator.java:151`, `BS/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:34`, `SP/bootstrap/idempotency/SampleIdempotencyConfig.java:34`; `jdbc` 값 main 0건, `6d27356e` | - | - | -| S6-#3a | Required | startup validator가 3 lifecycle·여러 패키지에 흩어짐, `StartupRule` 목록 없음 | 남음 | 19 → 16개: bootstrap 7(`BS/runtime/*Validator` 5, `OutboxCanonicalTransportRequirementValidator`, `TracingSamplingEnvironmentPostProcessor`), persistence-jpa 8(`JS/*Validator` 7, `JpaActivationEnvironmentPostProcessor`), cache-redis 1(`RedisReadinessGroupPostProcessor`). EPP 4, `InitializingBean` 1, `SmartInitializingSingleton` 11. `StartupRule` 타입 없음 | W3 | 모듈마다 `StartupRule { List violations(Environment) }` 목록 + runner 1개; bean이 필요한 검사만 bean으로 | +| S6-#3a | Required | startup validator가 3 lifecycle·여러 패키지에 흩어짐, `StartupRule` 목록 없음 | 완료 | Wave 3 W3-P22 (Wave 3 라운드 3 커밋): P22 W2 `7f39bfda`: `support.startup.StartupRule { phase(); summary(); remedy(); List violations(Environment) }` + 러너 하나 `StartupRuleRunner`(`StartupRuleAutoConfiguration`, support `AutoConfiguration.imports`). 환경만 읽는 검사 8개를 규칙으로: bootstrap `RuntimeNumericBoundsValidator`·`ErrorDetailExposureSafetyValidator`, persistence-jpa `RequiredEnvironmentValidator`·`FlywayProdSafetyValidator`·`OpenInViewSafetyValidator`·`PostgreSqlTransportSecurityValidator`·`PersistenceVendorProdSafetyValidator`·`HikariPoolConstraintValidator`. phase·종료 코드와 위반 문구는 유지(메시지 앞머리에 규칙 summary가 붙는 형태만 통일). bean이 필요한 검사(`SecretSourceValidator`, `StartupSafetyValidator`, `JpaDataSourceProfileValidator`, `JpaDangerousConfigurationGuard`)는 bean으로 유지, 부팅 전 EPP(`RuntimeEnvironmentProfileValidator`, `JpaActivationEnvironmentPostProcessor`, `TracingSamplingEnvironmentPostProcessor`, `RedisReadinessGroupPostProcessor`)는 EPP로 유지. `StartupRuleRunnerTest` 3건, 기존 검증기 테스트 전부 통과 | - | 모듈마다 `StartupRule { List violations(Environment) }` 목록 + runner 1개; bean이 필요한 검사만 bean으로 | | S6-#3b | Required | OSIV 검사 2벌, 뒤 검사의 local 예외는 죽은 코드 | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): 행동 보존 정리(FAIL→PASS 대상 아님): `OpenInViewSafetyValidator`(모든 profile 거부)를 정본으로 두고 `JpaDangerousConfigurationGuard`의 OSIV 분기·`OPEN_IN_VIEW_KEY` 삭제(`.../startup/JpaDangerousConfigurationGuard.java`), `JpaPlatformReport`는 validator 상수 사용. `OpenInViewSafetyValidatorTest.openInViewTrueFailsStartupUnderALocalConvenienceProfileToo` 추가(수정 전후 모두 PASS = guard의 local 예외가 죽은 코드였다는 증거). guard 테스트는 ddl-auto만 검사하도록 재작성. 학습 문서 `docs/study/postgresql-jpa-walkthrough.ko.md` 표 갱신 | - | 하나로: local 예외를 정책으로 쓸지 정해 `OpenInViewSafetyValidator`를 삭제하거나 guard의 OSIV 분기를 삭제 | | S6-#3c | Required | ddl-auto 검사 2벌 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): `JpaSchemaSafetyValidator`(+테스트) 삭제, `JpaDangerousConfigurationGuard`가 유일한 ddl-auto 검사. 기존 validator 테스트의 성질(prod 거부·blank 거부·대소문자·local 허용·`APP_DATASOURCE_DDL_AUTO` 명시·`PROFILE_MISMATCH`)을 guard 테스트로 옮김. `JpaDangerousConfigurationGuardTest.productionRefusesASchemaMutatingDdlAutoAsAProfileMismatchNamingTheEnvironmentKey` 등 10건 FAIL(guard가 `IllegalStateException`을 던짐)→PASS. `persistence-jpa/.../startup/JpaDangerousConfigurationGuard.java:46-66`. README 3곳 갱신 | - | guard 한 곳으로 합치고 `JpaSchemaSafetyValidator` 삭제 | | S6-#3d | Required | `isProdActive()` 5곳 복사 | 완료 | Wave 3 W3-P26 (Wave 3 라운드 2 커밋): 1줄 wrapper 삭제, 호출부에서 `RuntimeProfileSnapshot.from(environment).isProduction()` 직접 호출: `FlywayProdSafetyValidator`, `PersistenceVendorProdSafetyValidator`, `PostgreSqlTransportSecurityValidator`, `bootstrap/runtime/SecretSourceValidator`. `JpaSchemaSafetyValidator` 몫은 S6-#3c 삭제로 해소. `shared-contract` `RuntimeEnvironment.isProductionActive` 문서의 "isProdActive() copies" 언급은 역사 설명이라 유지. 동작 동일, 기존 테스트 통과 | - | 1줄 wrapper 삭제하고 호출부에서 직접 호출(S6-#3a와 함께) | @@ -1212,3 +1212,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P21-new-1 | 발견 | handler가 `Retry`를 답하면 Kafka consumer가 시도 횟수를 세지 않아 partition이 영구히 멈췄다. | 완료 | Wave 3 P21: 예외와 같은 시도 예산·격리 사용 | - | - | | P21-new-2 | 발견 | 다시 읽은 delivery가 항상 `deliveryAttempt=1`을 보고했다. | 완료 | Wave 3 P21 | - | - | | P21-new-3 | 발견 | `src/messaging/CLAUDE.md`가 `MessagingPublicSurfaceContractTest`를 인용 — 테스트는 app-bootstrap에 있다(P21은 없다고 보고). 통합 때 이 테스트가 P21 변경(reactive facade 삭제, leaf 병합, starter-kafka 공개 consumer seam)을 반영하지 못해 실패 → 기대값 수정, starter-kafka에 `api kafka-clients` 선언. | 남음 | Wave 3 라운드 3 통합 | W5 | messaging CLAUDE.md의 테스트 위치 문구를 app-bootstrap 경로로 | +| P22-new-1 | 발견 | bootstrap `SecretSourceValidator`가 persistence-jpa의 모듈 스위치를 읽어 `APP_DATASOURCE_PASSWORD` 필요 여부를 판정(모듈 지식이 bootstrap에). | 남음 | Wave 3 P22 결과 파일 | W3 | Redis처럼 persistence-jpa가 secret 요구를 기여. P20 | +| P22-new-2 | 발견 | `infra/redis-sdk/acl/application.acl`·`all-accounts.acl`이 pub/sub 삭제 뒤에도 `+@pubsub`·`&prod:*`를 준다(최소 권한 위반, fixture). | 남음 | Wave 3 P22 결과 파일 | W3 | ACL fixture에서 제거 후 topology lane 재실행. P20 | +| P22-new-3 | 발견 | redis-sdk 공개 API가 runtime 타입을 노출하면서 runtime을 `implementation`으로만 의존. `ca.spring-library`에 `api` 구성이 없어 한 줄로 못 고침. | 남음 | Wave 3 P22 결과 파일, 통합 때 시도 | W3 | 컨벤션에 `java-library` 적용 또는 공개 표면에서 runtime 타입 제거. P29 | +| ORCH-new-4 | 발견 | redis-sdk `RedisSdkModuleBoundaryTest`·`RedisSupportMatrixTest`가 옛 split package(`redis-runtime/.../redis/sdk`)를 훑음 — P22 worktree에서 통과, main 통합에서 `NoSuchFileException`(ORCH-new-2와 같은 유형: 저장소 파일을 읽지만 test inputs 미선언). | 남음 | 경로는 통합 때 수정(`redis-sdk` 하나) | W4 | 읽는 파일을 test `inputs`로 선언 | diff --git a/docs/superpowers/plans/2026-09-25-review-followup.md b/docs/superpowers/plans/2026-09-25-review-followup.md index 0acb088f..aec8b350 100644 --- a/docs/superpowers/plans/2026-09-25-review-followup.md +++ b/docs/superpowers/plans/2026-09-25-review-followup.md @@ -229,8 +229,8 @@ W1·W2 잔여 21행(Wave 2.5)은 P14로 1라운드에서 함께 처리한다. W1 | P23 | 3 | notification: SES → sesv2(결정 17), `persistence-notification` 추출, SRP | `S1-#4` `S1-#9` `S1-#10b` `S2-#1b` `S2-#6c` `S2-#8a` `S2-#13b` `S4-#3c` `S4-#4b` `S4-#9` `S4-#14b` `S4-#15` `S4-lead-3` `S4-lead-5` | | P27 | 3 | 빌드 잔여(결정 28·29·31): O3-5 나머지(`ca.release-provenance`·auxiliary → `jvm-test-suite`), messaging 카드 검증 leaf 테스트로, cosign 서명, `INTERNAL_ERROR` retryable=false, persistence-fileserver `ca.api-surface` | `BUILD-결론-1` `BUILD-O3-5` `X1-#7a` `X1-지도-readiness…` `BUILD-계획-C` `P15-new-3` `P16-new-6` | | P28 | 3 | 로컬 보안 파일시스템 primitive 공용화(보안 민감 재작성, P24에서 분리) + fileserver 잔여 | `S4-lead-2` `P24-new-2` `P25-new-2` `P24-new-3` `S6-#10a` `S1-#6b` `S1-#18b`(결정 32) `S2-#8a` `S2-#13b` `P23-new-1` `P23-new-2` | -| P29 | 4 | 빌드 잔여 2: auxiliary 레인 → Gradle `jvm-test-suite`(P27 중단분, WIP 패치 보관), build-logic 줄 수 판정 | `BUILD-O3-5` `BUILD-결론-1` | -| P20 | 4 | 3-B 설정 prefix `app.*`(결정 16), strict 바인딩 | `X2-P1-3c` `S3-lead-2` `S3-lead-4` `S6-#14` `P11-new-1` | +| P29 | 4 | 빌드 잔여 2: auxiliary 레인 → Gradle `jvm-test-suite`(P27 중단분, WIP 패치 보관), build-logic 줄 수 판정 | `BUILD-O3-5` `BUILD-결론-1` `P22-new-3` | +| P20 | 4 | 3-B 설정 prefix `app.*`(결정 16), strict 바인딩 | `X2-P1-3c` `S3-lead-2` `S3-lead-4` `S6-#14` `P11-new-1` `P22-new-1` `P22-new-2` | - [x] 라운드 1: P14 · P15 · P16 · P17 → 통합·검증·커밋 (2026-09-28, `9fdb0af4`·`c4a066df`·라운드 1 마무리 커밋) - [x] 라운드 2: P18 · P24 · P25 · P26 → 통합·검증·커밋 (2026-09-28~29, `4fb7943b`·`64a83918`·`25de288a`·`423a29c4`) diff --git a/src/.env.example b/src/.env.example index f30773b7..491d11f7 100644 --- a/src/.env.example +++ b/src/.env.example @@ -138,9 +138,6 @@ APP_CACHE_REDIS_NEGATIVE_TTL=10s APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT=200ms APP_LEASE_REDIS_COMMAND_TIMEOUT=200ms APP_LEASE_REDIS_CONTENTION_RETRY_AFTER=50ms -APP_REDIS_ADMIN_CREDENTIAL_REFERENCE= -APP_REDIS_ADMIN_ENABLED=false -APP_REDIS_BLOCKING_MAX_CONNECTIONS=32 APP_REDIS_DATABASE=0 APP_REDIS_MODE=standalone APP_REDIS_NAMESPACE_DOMAIN=shared @@ -150,11 +147,9 @@ APP_REDIS_NODES=localhost:6379 APP_REDIS_TIMEOUT_BATCH=2s APP_REDIS_TIMEOUT_FAST=500ms APP_REDIS_TIMEOUT_SCRIPT=1s -APP_REDIS_TRANSACTION_MAX_CONNECTIONS=16 APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE= APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=false APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE= -APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE= APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_COMMANDS=64 APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS=8 APP_REDIS_CAPACITY_REJECT_WHEN_DISCONNECTED=true @@ -166,7 +161,6 @@ APP_REDIS_LIFECYCLE_CONNECT_TIMEOUT=2s APP_REDIS_LIFECYCLE_DRAIN_TIMEOUT=6s APP_REDIS_LIFECYCLE_SHUTDOWN_QUIET_PERIOD=100ms APP_REDIS_LIFECYCLE_SHUTDOWN_TIMEOUT=3s -APP_REDIS_PUBSUB_BUFFER_CAPACITY=1024 APP_REDIS_SENTINEL_CREDENTIAL_REFERENCE= APP_REDIS_SENTINEL_MASTER_NAME= APP_REDIS_SENTINEL_NODES=app.redis.nodes diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index ec11b87d..494a02c9 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -22,25 +22,32 @@ Package root: `dev.caskeleton.adapter.outbound.cache`. - Keep the legacy cache router isolated while consumers migrate to semantic ports. - Reuse `adapter:outbound:support` for shared outbound concerns. - Depend on `:adapter:outbound:redis-runtime` for the shared topology client, connection lifecycle, - low-level gateway and conditional Redis runtime composition used by the semantic adapters. + the eight `SemanticRedisCommands` and conditional Redis runtime composition used by the semantic + adapters. - Keep the general-purpose typed SDK in the separate library leaf `:adapter:outbound:redis-sdk` (see its `README.md`). This leaf does not depend on it in any configuration, tests included; the SDK's tests and lanes live in that leaf. -## Redis runtime and optional typed SDK (`…cache.redis.sdk`) +## Redis runtime (`…cache.redis.runtime`) and optional typed SDK (`…cache.redis.sdk`) -The package namespace is shared across two registered Gradle leaves, but their deployment roles are -different. +Two registered leaves, two packages, one direction: the SDK builds on the runtime, the runtime knows +nothing of the SDK (`RedisRuntimePackageBoundaryTest` in the runtime holds that direction). -- `:adapter:outbound:redis-runtime` is production substrate: settings binding, credential - resolution, topology clients, `RedisRuntimeOwner`, the low-level command gateway and health. - `cache-redis` depends on this leaf. -- `:adapter:outbound:redis-sdk` owns the optional general-purpose typed API, command catalog/policy, - operation budgets, command guard, raw/admin surfaces, programmability and extensions. - `cache-redis` does **not** depend on it, in production or in tests. -- The semantic cache/idempotency/rate-limit/lease/realtime adapters in this leaf intentionally call - the runtime gateway through their own closed semantic programs/contracts. They do not pass through - `CommandPolicyGuard`, and `redis-command-policy.yml` does not control those semantic adapters. +- `:adapter:outbound:redis-runtime` is production substrate: `RedisRuntimeSettings` binding, + credential resolution, topology clients, `RedisRuntimeOwner` with the runtime's own lanes + (`RedisConnectionKind.REGULAR`, `SCRIPT`), `SemanticRedisCommands` (the eight commands this leaf + and the health contributor send) and health. `cache-redis` depends on this leaf. +- `:adapter:outbound:redis-sdk` owns the optional general-purpose typed API: `RedisCommandGateway` + (extends `SemanticRedisCommands`), command catalog/policy, operation budgets, command guard, + raw/admin surfaces, programmability and extensions — and its own lanes (`RedisSdkLane`: blocking, + transaction, admin) and admin account, which a service contributes to the runtime as + `RedisLaneContribution`/`RedisAccountContribution` beans (`RedisSdkComposition`). `cache-redis` + does **not** depend on it, in production or in tests. +- The semantic cache/idempotency/rate-limit/lease adapters in this leaf send the runtime's + `SemanticRedisCommands` through their own closed semantic programs (`RegisteredLuaScript`). They + do not pass through `CommandPolicyGuard`, and `redis-command-policy.yml` does not control them. +- Which roles need Redis for correctness is this leaf's `RedisCorrectnessRoleSelectors`, registered + in `META-INF/spring.factories` as the runtime's `RedisCorrectnessRequirement`. The typed SDK described in `docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md` remains an optional library @@ -86,9 +93,9 @@ in `docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md`. only a pre-filter — and all of them build commands through `ExtensionCommandRunner` so the guard sees their keys. Search is the exception that proves it: an index is not a key, so its name is namespaced by `LettuceRedisSearchOperations` itself. -- `RedisSdkModuleBoundaryTest` (in `redis-sdk`) scans both `redis-runtime` and `redis-sdk` source - roots and enforces the internal package graph, driver containment, the absence of an arbitrary string - command surface, and the designed module list. +- `RedisSdkModuleBoundaryTest` (in `redis-sdk`) scans the `redis-sdk` source root and enforces the + internal package graph, driver containment, the absence of an arbitrary string command surface, + and the designed module list. - Decisions that must not be changed without revisiting the design: no unbounded `entries`, `members`, `rangeAll`, or `keys`; no optional R2 permit or budget; no arbitrary command string overload; no automatic retry of a non-idempotent write after a timeout; no real key in a metric or @@ -113,9 +120,9 @@ in `docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md`. ## Tests -Focused tests drive the semantic adapters against the in-memory gateway from -`testFixtures(project(':adapter:outbound:redis-runtime'))` (`InMemoryGatewayAccess`), the one fake -of `RedisCommandGateway`. R1/R2 promotion requires a separate real Redis service lane; it may never +Focused tests drive the semantic adapters against `InMemorySemanticRedisCommands` from +`testFixtures(project(':adapter:outbound:redis-runtime'))`, the one fake of `SemanticRedisCommands`, +served through `StubRedisRuntimeClient`. R1/R2 promotion requires a separate real Redis service lane; it may never be silently skipped when selected. `redisTopologyTest` is the only real-server lane, declared through `ca.redis-topology-lane`. This @@ -137,7 +144,7 @@ containing the same text satisfied it. A hand-maintained per-mode floor on the e ## Composition -`RedisSdkAutoConfiguration` now belongs to `:adapter:outbound:redis-runtime`. It is the only +`RedisRuntimeAutoConfiguration` now belongs to `:adapter:outbound:redis-runtime`. It is the only place Redis settings and the shared runtime substrate come into existence, and it exists only while `app.redis.enabled` (env `APP_REDIS_ENABLED`, default `true` — the module is on when present) is true. It builds the topology client, connection owner and health contributors; `RedisCapabilityConfig` @@ -153,19 +160,19 @@ Every capability renders its keys under the one namespace from `app.redis.namesp prefix tokens: four capabilities each joining two free-form strings produced four different key shapes, and the deployment's ACL pattern matched none of them. -Lanes authenticate as different accounts. `RedisConnectionKind.credentialRole()` maps the lane to a -`RedisCredentialRole`, and the topology factory builds one client per *configured* role — so a -single-account deployment still gets exactly one client and one event loop. The `SCRIPT` lane is +Lanes authenticate as different accounts. `RedisLane.account()` names the lane's `RedisAccount`, +and the topology factory builds one client per *configured* account — so a single-account +deployment still gets exactly one client and one event loop. The `SCRIPT` lane is the reason it exists: `SCRIPT LOAD` and `EVALSHA` belong to the advanced account, so the account that reads a cache entry cannot execute a script. -A Cluster transaction runs on one node, so `RedisTransactionRunner` derives a routing key from the -watched keys (or an explicit `RedisSlotTag`) and pins the `TRANSACTION` lane to the node that owns -that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's +A Cluster transaction runs on one node, so the SDK's `RedisTransactionRunner` derives a routing key +from the watched keys (or an explicit `RedisSlotTag`) and borrows `RedisSdkLane.TRANSACTION`, which +is pinned to its key's owner, on the node that owns that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's node. -`RedisSdkSettings` -must never carry a class-level `@ConfigurationProperties`: `RedisSdkAutoConfiguration` binds it, so +`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 package would bind it regardless (bootstrap's `@ConfigurationPropertiesScan` lists only `dev.caskeleton.bootstrap.*` packages). Role selectors (cache binding, session auth-mode, idempotency/lease/rate-limit provider) diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 4d17f2be..044cef1b 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -4,15 +4,17 @@ This module is the **semantic Redis capability adapter**, not a general Redis SD The Redis implementation is deliberately split into three Gradle leaves: -- `:adapter:outbound:redis-runtime` — shipped connection/topology/settings/gateway substrate. +- `:adapter:outbound:redis-runtime` (`dev.caskeleton.adapter.outbound.cache.redis.runtime`) — + shipped connection/topology/settings substrate: `RedisRuntimeSettings`, the lane owner, and the + eight `SemanticRedisCommands` this module sends. It knows nothing of the typed SDK. - `:adapter:outbound:cache-redis` — shipped application-facing cache, rate-limit, lease and idempotency adapters. - `:adapter:outbound:redis-sdk` — optional typed/general-purpose SDK. It is not on the default application runtime graph. The default application therefore does not acquire the optional SDK's command policy merely by -selecting a semantic Redis capability. Semantic adapters call the runtime gateway directly and own -their own correctness rules. +selecting a semantic Redis capability. Semantic adapters call the runtime's `SemanticRedisCommands` +directly and own their own correctness rules. ## Using it as a capability module — what it provides, the one line, the env keys @@ -29,12 +31,14 @@ runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbou - the port implementations the role selectors ask for — `CacheRegionPort` (cache), `EdgeRateLimitPort` (rate limit), `DistributedLeasePort` (lease), `IdempotencyStorePort` (idempotency; the application builds the executor over it); -- `RedisCapabilityConfig` (`AutoConfiguration.imports`, after `RedisSdkAutoConfiguration`). With - `APP_REDIS_ENABLED=false` neither it nor redis-runtime's `RedisSdkAutoConfiguration` contributes a +- `RedisCapabilityConfig` (`AutoConfiguration.imports`, after `RedisRuntimeAutoConfiguration`). With + `APP_REDIS_ENABLED=false` neither it nor redis-runtime's `RedisRuntimeAutoConfiguration` contributes a bean — no settings, client, connection, thread or health contributor. The module pulls no Spring Data Redis, so there is no Boot Redis auto-configuration to exclude; - the readiness contribution `RedisReadinessGroupPostProcessor` (this module's `spring.factories`): - `redisRequired` joins the readiness group only when a correctness role selects Redis; + `redisRequired` joins the readiness group only when a correctness role selects Redis. Which roles + those are is this module's `RedisCorrectnessRoleSelectors`, registered in the same file as the + runtime's `RedisCorrectnessRequirement` — the runtime asks, it does not list selectors; - the shipped settings `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, `app.rate-limit.*`, and the Redis parts of `ca-skeleton.capabilities.*` (cache, lease, rate-limit, the Redis idempotency store's tuning). The support leaf's `ModuleDefaultsEnvironmentPostProcessor` diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index cf4b291d..4b66c1b5 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -18,6 +18,8 @@ dependencies { // The in-memory gateway and the topology endpoint the semantic adapter tests run against. testImplementation testFixtures(project(':adapter:outbound:redis-runtime')) + // The lease port's ownership contract, which the Redis adapter runs like the in-memory fake. + testImplementation testFixtures(project(':application-core')) // RedisReadinessGroupPostProcessorTest boots a real actuator health context: the readiness group // and its membership validation are what the post-processor exists to keep bootable. testImplementation 'org.springframework.boot:spring-boot-starter-actuator' @@ -49,6 +51,8 @@ dependencies { // validation, tag selection, TLS mapping and no-skip enforcement. The leaf names the classes each // of its lanes exists to run. Sentinel and TLS are qualified by redis-runtime and redis-sdk. redisTopologyLane { - requiredClasses 'standalone', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest' - requiredClasses 'cluster', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest' + requiredClasses 'standalone', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest', + 'LiveRedisDistributedLeaseContractTest' + requiredClasses 'cluster', 'LiveRedisSemanticPortsTest', 'LiveRedisSemanticScriptAclProbeTest', + 'LiveRedisDistributedLeaseContractTest' } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScript.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScript.java new file mode 100644 index 00000000..07becbbb --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScript.java @@ -0,0 +1,179 @@ +package dev.caskeleton.adapter.outbound.cache.redis; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; + +/** + * One Lua program the semantic adapters run by digest: load once, {@code EVALSHA} after, and load + * again exactly once when the server says it no longer has it. + * + *

A server forgets its scripts on restart, on {@code SCRIPT FLUSH}, and on failover to a replica + * that never saw the load. The only signal is a {@code NOSCRIPT} reply, and it does not always + * arrive as Lettuce's {@code RedisNoScriptException}: through some proxies and wrapped driver paths + * it is a plain command failure whose message starts with {@code NOSCRIPT}. Four hand-written + * copies of this helper disagreed about that — one checked the message, three only the type — so a + * lease, a rate limit or an idempotency claim failed on a reply the cache recovered from. + * + *

The reply decoding the three array-returning programs share lives here too ({@link #number}, + * {@link #text}): a Lua integer arrives as a {@code Long}, a status or a string as bytes, and each + * program used to carry its own copy of the conversion. + */ +public final class RegisteredLuaScript { + + private final byte[] source; + + private final AtomicReference digest = new AtomicReference<>(); + + /** + * Creates the program. + * + * @param source the Lua source, which never changes for the life of this object + */ + public RegisteredLuaScript(String source) { + this.source = + Objects.requireNonNull(source, "source must be non-null").getBytes(StandardCharsets.UTF_8); + } + + /** + * Runs the program on one key and returns its array reply. + * + * @param commands the commands of a borrowed SCRIPT lease + * @param key the single key the program touches + * @param arguments the program's arguments + * @return the reply values + */ + public CompletionStage> evaluateForList( + SemanticRedisCommands commands, byte[] key, List arguments) { + return run( + commands, (loaded, server) -> server.evaluateRegisteredForList(loaded, key, arguments)); + } + + /** + * Runs the program on one key and returns its integer reply. + * + * @param commands the commands of a borrowed lease + * @param key the single key the program touches + * @param arguments the program's arguments + * @return the integer reply + */ + public CompletionStage evaluateForLong( + SemanticRedisCommands commands, byte[] key, List arguments) { + return run( + commands, (loaded, server) -> server.evaluateRegisteredForLong(loaded, key, arguments)); + } + + private CompletionStage run( + SemanticRedisCommands commands, + BiFunction> evaluation) { + return digest(commands) + .thenCompose(loaded -> evaluation.apply(loaded, commands)) + .handle( + (reply, failure) -> { + if (failure == null) { + return CompletableFuture.completedFuture(reply); + } + if (!scriptMissing(failure)) { + return CompletableFuture.failedFuture(failure); + } + // Once. A server that forgets a script it was just given is not going to remember it + // on the third try, and a loop here would hide that. + digest.set(null); + return digest(commands).thenCompose(loaded -> evaluation.apply(loaded, commands)); + }) + .thenCompose(stage -> stage); + } + + private CompletionStage digest(SemanticRedisCommands commands) { + String cached = digest.get(); + if (cached != null) { + return CompletableFuture.completedFuture(cached); + } + return commands + .loadScript(source) + .thenApply( + loaded -> { + digest.set(loaded); + return loaded; + }); + } + + /** + * Reports whether a failure is the server saying it does not have the script. + * + * @param failure the failure, possibly wrapped by the future that carried it + * @return {@code true} for a {@code NOSCRIPT} reply, typed or not + */ + static boolean scriptMissing(Throwable failure) { + Throwable cause = failure; + while ((cause instanceof CompletionException || cause instanceof ExecutionException) + && cause.getCause() != null) { + cause = cause.getCause(); + } + return cause instanceof io.lettuce.core.RedisNoScriptException + || (cause.getMessage() != null && cause.getMessage().startsWith("NOSCRIPT")); + } + + /** + * Reads an integer element of a program's reply. + * + * @param value the element: a {@code Long}, or bytes carrying digits + * @return the number, {@code 0} for an empty element + * @throws IllegalStateException when the element is neither + */ + public static long number(Object value) { + if (value instanceof Number n) { + return n.longValue(); + } + if (value instanceof byte[] bytes) { + String text = new String(bytes, StandardCharsets.UTF_8).strip(); + return text.isEmpty() ? 0L : Long.parseLong(text); + } + throw new IllegalStateException( + "a registered program answered with an unexpected value type: " + + (value == null ? "null" : value.getClass().getName())); + } + + /** + * Reads a string element of a program's reply. + * + * @param value the element: bytes, or anything else printed as-is + * @return the text, empty for {@code null} + */ + public static String text(Object value) { + if (value instanceof byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + return value == null ? "" : String.valueOf(value); + } + + /** + * Checks that a program's array reply has the shape it promises. + * + * @param reply the reply + * @param size the number of elements the program returns + * @param program the program's name, for the failure message + * @return the reply + * @throws IllegalStateException when the reply is absent or short + */ + public static List requireShape(List reply, int size, String program) { + if (reply == null || reply.size() < size) { + throw new IllegalStateException( + "the " + + program + + " program answered with " + + (reply == null ? "nothing" : reply.size() + " values") + + "; " + + size + + " were expected"); + } + return reply; + } +} 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 new file mode 100644 index 00000000..59d38f78 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/SemanticRedisCall.java @@ -0,0 +1,168 @@ +package dev.caskeleton.adapter.outbound.cache.redis; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +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 java.time.Duration; +import java.util.Objects; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** + * One semantic adapter call on Redis: borrow a lane, send, wait a bounded time, and turn every way + * that can fail into one of two answers the caller can act on. + * + *

The two answers are the whole point, and they are not "success" and "failure": + * + *

    + *
  • not sent — nothing can have happened: the runtime refused a lease before any command + * existed, or the call failed before it {@linkplain Session#markSent() marked} the write as + * handed to the driver. The caller may treat the operation as unavailable and retry it. + *
  • unknown — the command may have run. A timeout, a lost reply, an interrupted wait: + * the caller must not be told "failed", because retrying an effect that already landed is how + * it happens twice. + *
+ * + *

Sixteen hand-written copies of this frame — borrow, {@code .get(timeout)}, catch {@code + * InterruptedException}, catch the runtime's refusal, catch everything else — lived in the four + * 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. + */ +public final class SemanticRedisCall { + + private final RedisRuntimeOwner owner; + private final RedisLane lane; + private final Duration timeout; + private final String capability; + + /** + * Creates the call frame for one capability. + * + * @param owner the runtime owner leases come from + * @param lane the lane this capability's calls run on + * @param timeout the ceiling on each awaited reply + * @param capability the capability name the failure log carries + */ + public SemanticRedisCall( + RedisRuntimeOwner owner, RedisLane lane, Duration timeout, String capability) { + this.owner = Objects.requireNonNull(owner, "runtime owner must be non-null"); + this.lane = Objects.requireNonNull(lane, "lane must be non-null"); + this.timeout = Objects.requireNonNull(timeout, "timeout must be non-null"); + this.capability = Objects.requireNonNull(capability, "capability must be non-null"); + } + + /** + * 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. + * + * @param operation the semantic operation, for the failure log + * @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 effect(String operation, Body body, Supplier notSent, Supplier unknown) { + return call(operation, body, notSent, unknown, true); + } + + /** + * Runs a call that decides for itself when its effect was handed to the driver. + * + * @param operation the semantic operation, for the failure log + * @param body what to send, and how to read the reply; calls {@link Session#markSent()} before + * the command whose loss would leave the outcome unknown + * @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 run(String operation, Body body, Supplier notSent, Supplier unknown) { + return call(operation, body, notSent, unknown, false); + } + + private R call( + String operation, + 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(); + } catch (RedisLaneUnavailableException refused) { + RedisSemanticFailureLogger.report(capability, operation, refused); + return notSent.get(); + } catch (Exception failure) { + RedisSemanticFailureLogger.report(capability, operation, failure); + return session.sent ? unknown.get() : notSent.get(); + } + } + + /** What a call sends, given the borrowed connection. */ + @FunctionalInterface + public interface Body { + + /** + * Sends and reads. + * + * @param session the borrowed connection and its bounded wait + * @return the answer + * @throws Exception any failure, classified by the frame + */ + R apply(Session session) throws Exception; + } + + /** The borrowed connection, for the duration of one call. */ + public final class Session { + + private RedisLease lease; + private boolean sent; + + private Session() {} + + /** + * Returns the commands of the borrowed connection. + * + * @return the commands + */ + public SemanticRedisCommands commands() { + return lease.commands(); + } + + /** + * Waits for a reply, no longer than the call's timeout. + * + * @param reply the pending reply + * @param the reply type + * @return the reply + * @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); + } + + /** + * Records that the command whose loss leaves the outcome unknown is about to be sent. + * + *

A failure before this — a refused lease, a failed read that precedes the write — wrote + * nothing. + */ + public void markSent() { + sent = true; + } + } +} 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 df96900a..05ca89da 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 @@ -1,13 +1,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.RegisteredLuaScript; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; /** Atomic cache mutations that cannot be expressed as one ordinary Redis command. */ final class CacheScripts { @@ -25,10 +22,11 @@ final class CacheScripts { return 1 """; - private final AtomicReference replaceIfObservedDigest = new AtomicReference<>(); + private final RegisteredLuaScript replaceIfObserved = + new RegisteredLuaScript(REPLACE_IF_OBSERVED); CompletionStage replaceIfObserved( - RedisCommandGateway gateway, + SemanticRedisCommands commands, byte[] key, String observation, byte[] replacement, @@ -38,51 +36,8 @@ final class CacheScripts { observation.getBytes(StandardCharsets.US_ASCII), replacement, Long.toString(ttlMillis).getBytes(StandardCharsets.US_ASCII)); - return digest(gateway) - .thenCompose( - loaded -> - gateway - .evaluateRegisteredForLong(loaded, key, arguments) - .handle( - (reply, failure) -> - failure == null - ? CompletableFuture.completedFuture(reply) - : reload(gateway, key, arguments, failure)) - .thenCompose(stage -> stage)) + return replaceIfObserved + .evaluateForLong(commands, key, arguments) .thenApply(applied -> applied != null && applied == 1L); } - - private CompletionStage digest(RedisCommandGateway gateway) { - String cached = replaceIfObservedDigest.get(); - if (cached != null) { - return CompletableFuture.completedFuture(cached); - } - return gateway - .loadScript(REPLACE_IF_OBSERVED.getBytes(StandardCharsets.UTF_8)) - .thenApply( - loaded -> { - replaceIfObservedDigest.set(loaded); - return loaded; - }); - } - - private CompletionStage reload( - RedisCommandGateway gateway, byte[] key, List arguments, Throwable failure) { - if (!scriptMissing(failure)) { - return CompletableFuture.failedFuture(failure); - } - replaceIfObservedDigest.set(null); - return digest(gateway) - .thenCompose(loaded -> gateway.evaluateRegisteredForLong(loaded, key, arguments)); - } - - private static boolean scriptMissing(Throwable failure) { - Throwable cause = failure; - while ((cause instanceof CompletionException || cause instanceof ExecutionException) - && cause.getCause() != null) { - cause = cause.getCause(); - } - return cause instanceof io.lettuce.core.RedisNoScriptException - || (cause.getMessage() != null && cause.getMessage().startsWith("NOSCRIPT")); - } } 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 d46e2891..e680d83c 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 @@ -1,11 +1,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache; -import dev.caskeleton.adapter.outbound.cache.redis.RedisSemanticFailureLogger; +import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall; import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.application.cache.AuthoritativeAbsence; import dev.caskeleton.application.cache.CacheInvalidationOutcome; import dev.caskeleton.application.cache.CacheLookup; @@ -19,7 +18,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Objects; -import java.util.concurrent.TimeUnit; import java.util.function.Function; /** @@ -54,7 +52,7 @@ import java.util.function.Function; */ public final class RedisCacheRegionAdapter implements CacheRegionPort { - private final RedisRuntimeOwner owner; + private final SemanticRedisCall call; private final CacheKeys keys; @@ -72,8 +70,6 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort implements CacheRegionPort implements CacheRegionPort 0) { throw new IllegalArgumentException( "the soft TTL must not exceed the hard TTL: an entry cannot stop being fresh after it has" @@ -123,27 +122,23 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort lookup(K key) { Objects.requireNonNull(key, "key must be non-null"); Instant now = clock.instant(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - resolveGeneration(lease, now); - byte[] stored = - lease - .gateway() - .get(keys.entryKey(keyDigest.apply(key))) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - if (stored == null) { - return new CacheLookup.Miss<>( - CacheLookup.MissReason.ABSENT, CacheWriteCondition.unavailable()); - } - return interpret(stored, now); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return unavailable(); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("cache", "lookup", failure); - // Degraded, not broken. The caller loads from the source and carries on. - return unavailable(); - } + // A read changed nothing, whether or not it reached the server: degraded, not broken. The + // caller + // loads from the source and carries on. + return call.run( + "lookup", + session -> { + resolveGeneration(session, now); + byte[] stored = + session.await(session.commands().get(keys.entryKey(keyDigest.apply(key)))); + if (stored == null) { + return new CacheLookup.Miss<>( + CacheLookup.MissReason.ABSENT, CacheWriteCondition.unavailable()); + } + return interpret(stored, now); + }, + this::unavailable, + this::unavailable); } private CacheLookup interpret(byte[] stored, Instant now) { @@ -223,98 +218,70 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort 0 ? ttl : softTtl; byte[] physicalKey = keys.entryKey(keyDigest.apply(key)); - // Whether the write command itself was handed to the driver. A failure before that point — - // lane refusal, connection, the generation read — wrote nothing. - boolean sent = false; - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - resolveGeneration(lease, now); - CacheEnvelope envelope = - new CacheEnvelope( - CacheEnvelope.CURRENT_SCHEMA_VERSION, - metadata.sourceRevision(), - keys.generation(), - now.plus(effectiveSoft), - now.plus(ttl), - absence, - payload); - Boolean applied; - sent = true; - if (metadata.intent() == CacheRecordIntent.ONLY_IF_OBSERVED) { - // Compare and replacement are one server-side execution. A GET followed by SET would let a - // concurrent writer land between them and then be overwritten by this stale source load. - applied = - scripts - .replaceIfObserved( - lease.gateway(), - physicalKey, - metadata.observedToken().value(), - envelope.encode(), - ttl.toMillis()) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - } else { - applied = - lease - .gateway() - .set( - physicalKey, - envelope.encode(), - presenceOf(metadata.intent()), - // The physical TTL is the hard expiry and nothing else. - new dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Expiration - .After(ttl)) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - } - return Boolean.TRUE.equals(applied) - ? CacheRecordOutcome.RECORDED - : CacheRecordOutcome.NOT_RECORDED_CONDITION; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return sent ? CacheRecordOutcome.INDETERMINATE : CacheRecordOutcome.DEGRADED_UNAVAILABLE; - } catch (Exception failure) { - RedisSemanticFailureLogger.report("cache", "record", failure); - return sent ? CacheRecordOutcome.INDETERMINATE : CacheRecordOutcome.DEGRADED_UNAVAILABLE; - } + // The write is marked sent only when the write command itself is handed to the driver. A + // failure before that point — lane refusal, connection, the generation read — wrote nothing. + return call.run( + "record", + session -> { + resolveGeneration(session, now); + CacheEnvelope envelope = + new CacheEnvelope( + CacheEnvelope.CURRENT_SCHEMA_VERSION, + metadata.sourceRevision(), + keys.generation(), + now.plus(effectiveSoft), + now.plus(ttl), + absence, + payload); + session.markSent(); + Boolean applied = + metadata.intent() == CacheRecordIntent.ONLY_IF_OBSERVED + // Compare and replacement are one server-side execution. A GET followed by SET + // would let a concurrent writer land between them and then be overwritten by + // this stale source load. + ? session.await( + scripts.replaceIfObserved( + session.commands(), + physicalKey, + metadata.observedToken().value(), + envelope.encode(), + ttl.toMillis())) + // The physical TTL is the hard expiry and nothing else. + : session.await( + session + .commands() + .set(physicalKey, envelope.encode(), presenceOf(metadata.intent()), ttl)); + return Boolean.TRUE.equals(applied) + ? CacheRecordOutcome.RECORDED + : CacheRecordOutcome.NOT_RECORDED_CONDITION; + }, + () -> CacheRecordOutcome.DEGRADED_UNAVAILABLE, + () -> CacheRecordOutcome.INDETERMINATE); } - private static dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.WritePresence + private static dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence presenceOf(CacheRecordIntent intent) { return intent == CacheRecordIntent.ONLY_IF_ABSENT - ? dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.WritePresence.IF_ABSENT - : dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.WritePresence.ALWAYS; + ? dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.IF_ABSENT + : dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.ALWAYS; } @Override public CacheInvalidationOutcome invalidate(K key) { Objects.requireNonNull(key, "key must be non-null"); - boolean sent = false; - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - byte[] physicalKey = keys.entryKey(keyDigest.apply(key)); - sent = true; - byte[] removed = - lease - .gateway() - .getAndDelete(physicalKey) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return removed == null - ? CacheInvalidationOutcome.ALREADY_ABSENT - : CacheInvalidationOutcome.INVALIDATED; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return invalidationFailure(sent); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("cache", "invalidate", failure); - return invalidationFailure(sent); - } - } - - // A lost reply to a sent delete or generation bump may have applied it. - private static CacheInvalidationOutcome invalidationFailure(boolean sent) { - return sent - ? CacheInvalidationOutcome.INDETERMINATE - : CacheInvalidationOutcome.DEGRADED_UNAVAILABLE; + return call.run( + "invalidate", + session -> { + byte[] physicalKey = keys.entryKey(keyDigest.apply(key)); + session.markSent(); + byte[] removed = session.await(session.commands().getAndDelete(physicalKey)); + return removed == null + ? CacheInvalidationOutcome.ALREADY_ABSENT + : CacheInvalidationOutcome.INVALIDATED; + }, + () -> CacheInvalidationOutcome.DEGRADED_UNAVAILABLE, + // A lost reply to a sent delete may have applied it. + () -> CacheInvalidationOutcome.INDETERMINATE); } @Override @@ -323,24 +290,17 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort { + session.markSent(); + Long generation = session.await(session.commands().incrementBy(keys.generationKey(), 1)); + keys.observeGeneration(generation, clock.instant()); + return CacheInvalidationOutcome.INVALIDATED; + }, + () -> CacheInvalidationOutcome.DEGRADED_UNAVAILABLE, + // A lost reply to a sent generation bump may have applied it. + () -> CacheInvalidationOutcome.INDETERMINATE); } /** @@ -352,16 +312,11 @@ public final class RedisCacheRegionAdapter implements CacheRegionPort redisDefaultCacheRegion( RedisRuntimeOwner owner, - RedisSdkSettings sdk, + RedisRuntimeSettings redis, RedisCapabilitySettings capabilities, SecretSourcePort secretSource, Clock clock) { RedisCapabilitySettings.Cache cache = capabilities.getCache(); cache.validate(); RedisKeys.KeyDigest digest = - RedisKeys.KeyDigest.of(secretSource, cache.getKeyHmacSecretReference(), "cache", sdk); + RedisKeys.KeyDigest.of(secretSource, cache.getKeyHmacSecretReference(), "cache", redis); return new RedisCacheRegionAdapter<>( owner, new RedisCacheRegionAdapter.CacheKeys( - RedisKeys.namespaceOf(sdk), cache.getSemanticRegion(), cache.getKeyVersion()), + RedisKeys.namespaceOf(redis), cache.getSemanticRegion(), cache.getKeyVersion()), digest::of, value -> value, stored -> stored, diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java index b268d693..74fa46ff 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.application.outbound.SecretSourcePort; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -26,16 +26,17 @@ import org.springframework.context.annotation.Import; * itself. With the switch off this module contributes no bean at all. * *

This class is the composition point only: it holds the switch, binds the settings once, - * bridges the secret backend into the SDK, and imports one configuration per capability. It used to - * hold all four capabilities plus rate-limit policy compilation and the key digest — 376 lines, in - * a leaf whose Notification platform had already been split into nine focused configurations. The - * decomposition pattern existed; this was simply where it had not been applied (BOOT-007). + * bridges the secret backend into the Redis runtime, and imports one configuration per capability. + * It used to hold all four capabilities plus rate-limit policy compilation and the key digest — 376 + * lines, in a leaf whose Notification platform had already been split into nine focused + * configurations. The decomposition pattern existed; this was simply where it had not been applied + * (BOOT-007). * *

The namespace comes from {@code app.redis.namespace} for every capability. That is the change * that makes the ACL pattern meaningful: one prefix, {@code {environment}:{service}:{domain}}, that * the deployment's {@code ~} pattern can actually fence. */ -@AutoConfiguration(after = RedisSdkAutoConfiguration.class) +@AutoConfiguration(after = RedisRuntimeAutoConfiguration.class) @EnableConfigurationProperties(RedisCapabilitySettings.class) // The global switch, not a role selector. A role selector says which capability composes; it // never says Redis exists. @@ -52,29 +53,40 @@ import org.springframework.context.annotation.Import; public class RedisCapabilityConfig { /** - * Bridges the deployment's configured secret backend into the Redis SDK. + * Bridges the deployment's configured secret backend into the Redis runtime. * - *

Without it the SDK falls back to reading the process environment directly, which quietly + *

Without it the runtime falls back to reading the process environment directly, which quietly * bypasses whichever backend {@code ca-skeleton.secret-source.strategy} selected — so a * deployment using a secret manager would resolve its Redis credential from an environment * variable that is not supposed to hold it. * * @param secretSource the configured backend - * @return the SDK's view of it + * @return the runtime's view of it */ @Bean - RedisSdkAutoConfiguration.RedisSecretSource redisSdkSecretSource(SecretSourcePort secretSource) { + RedisRuntimeAutoConfiguration.RedisSecretSource redisSecretSource(SecretSourcePort secretSource) { return secretSource::resolve; } + /** + * The production secrets of the Redis roles this deployment selected, for the composition root's + * secret guard — which checks them without knowing which Redis roles exist. + * + * @return the contribution + */ + @Bean + RedisProductionSecrets redisProductionSecrets() { + return new RedisProductionSecrets(); + } + @Bean @ConditionalOnMissingBean(RedisSemanticScriptAclProbe.class) RedisSemanticScriptAclProbe redisSemanticScriptAclProbe( - RedisRuntimeOwner owner, RedisCapabilitySettings capabilities, RedisSdkSettings sdk) { + RedisRuntimeOwner owner, RedisCapabilitySettings capabilities, RedisRuntimeSettings redis) { byte[] probeKey = - (RedisKeys.namespaceOf(sdk).prefix() + ":probe:{semantic-script}:acl") + (RedisKeys.namespaceOf(redis).prefix() + ":probe:{semantic-script}:acl") .getBytes(java.nio.charset.StandardCharsets.UTF_8); return new RedisSemanticScriptAclProbe( - owner, capabilities, probeKey, sdk.getTimeout().getScript()); + owner, capabilities, probeKey, redis.getTimeout().getScript()); } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCorrectnessRoleSelectors.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCorrectnessRoleSelectors.java new file mode 100644 index 00000000..b8adee57 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCorrectnessRoleSelectors.java @@ -0,0 +1,95 @@ +package dev.caskeleton.adapter.outbound.cache.redis.capability; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCorrectnessRequirement; +import java.util.List; +import org.springframework.core.env.Environment; + +/** + * The Redis roles, their selectors, and what each one requires. + * + *

Session, idempotency, rate limiting and leases produce a wrong answer when Redis is gone, not + * a slow one: a replayed payment, an unenforced quota, two holders of a lease. A deployment that + * selected any of them gates its readiness on Redis. The cache is a role too, but not a correctness + * one — its outage is degradation — so it needs its production secrets and nothing else. + * + *

This table used to be two: the selectors in {@code redis-runtime}, which therefore hard-coded + * selector keys of a module built on top of it, and a prefix switch in the composition root's + * secret guard. It is one now, here, with the capabilities it describes. The runtime is told only + * whether Redis is required ({@link RedisCorrectnessRequirement}, {@code + * META-INF/spring.factories}), and the secret guard only which secrets ({@link + * RedisProductionSecrets}). + */ +public final class RedisCorrectnessRoleSelectors implements RedisCorrectnessRequirement { + + /** + * One role. + * + * @param selector the property that selects the role's provider + * @param fallback the selector's value when the deployment set none + * @param selecting the value that selects Redis + * @param correctness whether serving without Redis would give wrong answers + * @param scripted whether the role runs registered programs on the SCRIPT lane + * @param productionSecrets the secrets the role needs under the {@code prod} profile + */ + record Role( + String selector, + String fallback, + String selecting, + boolean correctness, + boolean scripted, + List productionSecrets) { + + boolean selected(Environment environment) { + return selecting.equalsIgnoreCase(environment.getProperty(selector, fallback)); + } + } + + /** Every Redis role this module composes. */ + static final List ROLES = + List.of( + new Role( + "ca-skeleton.capabilities.cache.bindings.default", + "disabled", + "redis", + false, + false, + List.of("APP_CACHE_REDIS_PASSWORD", "APP_CACHE_REDIS_KEY_HMAC_SECRET")), + new Role( + "ca-skeleton.security.auth-mode", + "jwt", + "redis-session", + true, + false, + List.of("APP_SESSION_REDIS_PASSWORD", "APP_SESSION_REDIS_KEY_HMAC_SECRET")), + new Role( + "ca-skeleton.capabilities.idempotency.provider", + "disabled", + "redis", + true, + true, + List.of("APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET")), + new Role( + "ca-skeleton.capabilities.rate-limit.provider", + "disabled", + "redis", + true, + true, + List.of("APP_RATE_LIMIT_REDIS_PASSWORD", "APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET")), + new Role( + "ca-skeleton.capabilities.lease.provider", + "disabled", + "redis", + true, + true, + List.of("APP_LEASE_REDIS_KEY_HMAC_SECRET"))); + + @Override + public boolean required(Environment environment) { + return ROLES.stream().anyMatch(role -> role.correctness() && role.selected(environment)); + } + + @Override + public boolean requiresScriptLane(Environment environment) { + return ROLES.stream().anyMatch(role -> role.scripted() && role.selected(environment)); + } +} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java index ff0b413c..cfca107f 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java @@ -2,8 +2,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import dev.caskeleton.adapter.outbound.cache.redis.idempotency.IdempotencyScripts; import dev.caskeleton.adapter.outbound.cache.redis.idempotency.RedisIdempotencyStoreAdapter; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import dev.caskeleton.application.idempotency.IdempotencyStorePort; @@ -23,7 +23,7 @@ class RedisIdempotencyConfig { * The owner-safe request-replay store. * * @param owner the Redis runtime owner - * @param sdk the Redis SDK settings, which own the namespace + * @param redis the Redis runtime settings, which own the namespace * @param capabilities the capability settings * @param clock the clock lease deadlines are measured against * @return the store port @@ -34,7 +34,7 @@ class RedisIdempotencyConfig { havingValue = "redis") IdempotencyStorePort redisIdempotencyStore( RedisRuntimeOwner owner, - RedisSdkSettings sdk, + RedisRuntimeSettings redis, RedisCapabilitySettings capabilities, Clock clock) { RedisCapabilitySettings.Idempotency idempotency = capabilities.getIdempotency(); @@ -51,7 +51,7 @@ class RedisIdempotencyConfig { return new RedisIdempotencyStoreAdapter( owner, new RedisIdempotencyStoreAdapter.IdempotencyKeys( - RedisKeys.namespaceOf(sdk), idempotency.getKeyVersion()), + RedisKeys.namespaceOf(redis), idempotency.getKeyVersion()), new IdempotencyScripts(), clock, idempotency.getCommandTimeout()); 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 7943d8de..b7fd09c3 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 @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; import dev.caskeleton.application.outbound.SecretReference; import dev.caskeleton.application.outbound.SecretSourcePort; @@ -20,7 +20,7 @@ final class RedisKeys { private RedisKeys() {} /** The deployment's key namespace: {@code {environment}:{service}:{domain}}. */ - static RedisNamespace namespaceOf(RedisSdkSettings settings) { + static RedisNamespace namespaceOf(RedisRuntimeSettings settings) { return new RedisNamespace( settings.getNamespace().getEnvironment(), settings.getNamespace().getService(), @@ -38,7 +38,10 @@ final class RedisKeys { record KeyDigest(javax.crypto.Mac prototype) { static KeyDigest of( - SecretSourcePort secretSource, String reference, String capability, RedisSdkSettings sdk) { + SecretSourcePort secretSource, + String reference, + String capability, + RedisRuntimeSettings redis) { String name = secretName(reference, capability); String material = secretSource @@ -61,11 +64,11 @@ final class RedisKeys { // one-for-one onto the harder one. (material + '|' - + sdk.getNamespace().getEnvironment() + + redis.getNamespace().getEnvironment() + ':' - + sdk.getNamespace().getService() + + redis.getNamespace().getService() + ':' - + sdk.getNamespace().getDomain()) + + redis.getNamespace().getDomain()) .getBytes(StandardCharsets.UTF_8), "HmacSHA256")); return new KeyDigest(mac); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisLeaseConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisLeaseConfig.java index fda61003..efd8845c 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisLeaseConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisLeaseConfig.java @@ -2,8 +2,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import dev.caskeleton.adapter.outbound.cache.redis.lease.LeaseScripts; import dev.caskeleton.adapter.outbound.cache.redis.lease.RedisDistributedLeaseAdapter; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.application.lease.DistributedLeasePort; import java.time.Clock; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -18,7 +18,7 @@ class RedisLeaseConfig { * The distributed lease port. Efficiency only — it never supplies fencing. * * @param owner the Redis runtime owner - * @param sdk the Redis SDK settings, which own the namespace + * @param redis the Redis runtime settings, which own the namespace * @param capabilities the capability settings * @param clock the wall clock used for reporting instants * @return the lease port @@ -27,14 +27,14 @@ class RedisLeaseConfig { @ConditionalOnProperty(name = "ca-skeleton.capabilities.lease.provider", havingValue = "redis") DistributedLeasePort redisDistributedLeasePort( RedisRuntimeOwner owner, - RedisSdkSettings sdk, + RedisRuntimeSettings redis, RedisCapabilitySettings capabilities, Clock clock) { RedisCapabilitySettings.Lease lease = capabilities.getLease(); return new RedisDistributedLeaseAdapter( owner, new RedisDistributedLeaseAdapter.LeaseKeys( - RedisKeys.namespaceOf(sdk), lease.getKeyVersion()), + RedisKeys.namespaceOf(redis), lease.getKeyVersion()), new LeaseScripts(), clock, System::nanoTime, diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecrets.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecrets.java new file mode 100644 index 00000000..37ca5fd4 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecrets.java @@ -0,0 +1,24 @@ +package dev.caskeleton.adapter.outbound.cache.redis.capability; + +import dev.caskeleton.adapter.outbound.support.startup.RequiredProductionSecrets; +import java.util.List; +import org.springframework.core.env.Environment; + +/** + * The production secrets of the Redis roles this deployment selected. + * + *

A bean of this module's composition, so it exists only while {@code app.redis.enabled} is + * true: with Redis off nothing Redis-shaped is created, and demanding its credentials would fail a + * deployment over an adapter it never asked for. With Redis on, each selected role contributes its + * own secrets — a deployment that runs Redis for its cache owes nothing to the session store. + */ +public final class RedisProductionSecrets implements RequiredProductionSecrets { + + @Override + public List requiredSecrets(Environment environment) { + return RedisCorrectnessRoleSelectors.ROLES.stream() + .filter(role -> role.selected(environment)) + .flatMap(role -> role.productionSecrets().stream()) + .toList(); + } +} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisRateLimitConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisRateLimitConfig.java index 5a726e70..ec76c48e 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisRateLimitConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisRateLimitConfig.java @@ -1,15 +1,15 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; +import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitAlgorithm; +import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitFailurePolicy; import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitKeys; +import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitPolicy; import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitScripts; import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RedisEdgeRateLimitAdapter; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort; -import dev.caskeleton.shared.ratelimit.RateLimitAlgorithm; -import dev.caskeleton.shared.ratelimit.RateLimitFailurePolicy; -import dev.caskeleton.shared.ratelimit.RateLimitPolicy; import dev.caskeleton.shared.ratelimit.RateParameters; import java.time.Clock; import java.time.Duration; @@ -37,7 +37,7 @@ class RedisRateLimitConfig { * The provider-neutral edge rate limiter, backed by Redis. * * @param owner the Redis runtime owner - * @param sdk the Redis SDK settings, which own the namespace + * @param redis the Redis runtime settings, which own the namespace * @param capabilities the capability settings * @param clock the local clock used for caller deadlines and response reset instants * @param environment where the HTTP boundary's default policy id is read from @@ -49,7 +49,7 @@ class RedisRateLimitConfig { havingValue = "redis") EdgeRateLimitPort redisEdgeRateLimitPort( RedisRuntimeOwner owner, - RedisSdkSettings sdk, + RedisRuntimeSettings redis, RedisCapabilitySettings capabilities, Clock clock, Environment environment) { @@ -60,7 +60,7 @@ class RedisRateLimitConfig { String defaultPolicyId = environment.getProperty(DEFAULT_POLICY_ID, "api-default"); return new RedisEdgeRateLimitAdapter( owner, - new RateLimitKeys(RedisKeys.namespaceOf(sdk), rateLimit.getKeyVersion()), + new RateLimitKeys(RedisKeys.namespaceOf(redis), rateLimit.getKeyVersion()), policiesOf(rateLimit, defaultPolicyId), new RateLimitScripts(), clock, diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java index b9bb2d81..e0909cf6 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCorrectnessRoles; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCorrectnessRoles; import dev.caskeleton.adapter.outbound.support.startup.ReadinessGroup; import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; import org.springframework.boot.EnvironmentPostProcessor; 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 7025379e..f8a4179c 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,8 +1,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +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; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -63,13 +63,13 @@ final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton { try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { String digest = lease - .gateway() + .commands() .loadScript(PROBE_SCRIPT) .toCompletableFuture() .get(timeout.toNanos(), TimeUnit.NANOSECONDS); List reply = lease - .gateway() + .commands() .evaluateRegisteredForList(digest, probeKey, List.of()) .toCompletableFuture() .get(timeout.toNanos(), TimeUnit.NANOSECONDS); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index 3e65728e..b0a0681e 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -1,15 +1,11 @@ package dev.caskeleton.adapter.outbound.cache.redis.idempotency; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.RegisteredLuaScript; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; /** * The idempotency record's state machine, one atomic program per transition. @@ -186,122 +182,86 @@ public final class IdempotencyScripts { mine .. '|' .. tostring(redis.call('PTTL', KEYS[1]))} """; - private final Map> digests = - Map.of( - "claim", new AtomicReference<>(), - "transition", new AtomicReference<>(), - "release", new AtomicReference<>(), - "inspect", new AtomicReference<>()); + private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM); + private final RegisteredLuaScript transition = new RegisteredLuaScript(TRANSITION); + private final RegisteredLuaScript release = new RegisteredLuaScript(RELEASE); + private final RegisteredLuaScript inspect = new RegisteredLuaScript(INSPECT); - CompletionStage claim(RedisCommandGateway gateway, byte[] key, List arguments) { - return run(gateway, "claim", CLAIM, key, arguments); + CompletionStage claim(SemanticRedisCommands commands, byte[] key, List arguments) { + return run(claim, commands, key, arguments); } CompletionStage transition( - RedisCommandGateway gateway, byte[] key, List arguments) { - return run(gateway, "transition", TRANSITION, key, arguments); + SemanticRedisCommands commands, byte[] key, List arguments) { + return run(transition, commands, key, arguments); } - CompletionStage release(RedisCommandGateway gateway, byte[] key, List arguments) { - return run(gateway, "release", RELEASE, key, arguments); + CompletionStage release( + SemanticRedisCommands commands, byte[] key, List arguments) { + return run(release, commands, key, arguments); } - CompletionStage inspect(RedisCommandGateway gateway, byte[] key, List arguments) { - return run(gateway, "inspect", INSPECT, key, arguments); + CompletionStage inspect( + SemanticRedisCommands commands, byte[] key, List arguments) { + return run(inspect, commands, key, arguments); } - private CompletionStage run( - RedisCommandGateway gateway, String name, String source, byte[] key, List arguments) { - AtomicReference cache = digests.get(name); - if (cache == null) { - throw new IllegalArgumentException("unknown idempotency script: " + name); - } + private static CompletionStage run( + RegisteredLuaScript program, + SemanticRedisCommands commands, + byte[] key, + List arguments) { List encoded = new ArrayList<>(arguments.size()); for (String argument : arguments) { encoded.add(argument.getBytes(StandardCharsets.UTF_8)); } - return digest(gateway, source, cache) - .thenCompose(digest -> gateway.evaluateRegisteredForList(digest, key, encoded)) - .handle( - (reply, failure) -> - failure == null - ? CompletableFuture.completedFuture(reply) - : reload(gateway, source, cache, key, encoded, failure)) - .thenCompose(stage -> stage) - .thenApply(IdempotencyScripts::replyOf); + return program.evaluateForList(commands, key, encoded).thenApply(Reply::of); } - private CompletionStage> reload( - RedisCommandGateway gateway, - String source, - AtomicReference cache, - byte[] key, - List arguments, - Throwable failure) { - if (!scriptMissing(failure)) { - return CompletableFuture.failedFuture(failure); - } - cache.set(null); - return digest(gateway, source, cache) - .thenCompose(digest -> gateway.evaluateRegisteredForList(digest, key, arguments)); - } + /** + * What a program answered, parsed once. + * + *

The transition verdicts and, for {@code INSPECT}, the record's state. The programs speak in + * strings; the adapter speaks in this enum, so a misspelt status is a compile error rather than a + * {@code default} branch that quietly turns it into "unavailable". + */ + enum ScriptStatus { + ACQUIRED, + REPLAYED_ACQUIRE, + TAKEN_OVER, + COMPLETED_REPLAY, + IN_PROGRESS, + RECOVERY_REQUIRED, + FINGERPRINT_MISMATCH, + OWNER_OPERATION_CONFLICT, + APPLIED, + ALREADY, + ABSENT, + NOT_OWNER, + OPERATION_CONFLICT, + WRONG_STATE, + CLAIMED, + EXECUTING, + COMPLETED, + FAILED_RETRYABLE, + ABANDONED, + /** A status this adapter does not know: a newer program, or a corrupted reply. */ + UNRECOGNISED; - private static CompletionStage digest( - RedisCommandGateway gateway, String source, AtomicReference cache) { - String cached = cache.get(); - if (cached != null) { - return CompletableFuture.completedFuture(cached); + static ScriptStatus of(String text) { + for (ScriptStatus status : values()) { + if (status != UNRECOGNISED && status.name().equals(text)) { + return status; + } + } + return UNRECOGNISED; } - return gateway - .loadScript(source.getBytes(StandardCharsets.UTF_8)) - .thenApply( - loaded -> { - cache.set(loaded); - return loaded; - }); - } - - private static boolean scriptMissing(Throwable failure) { - Throwable cause = failure; - while ((cause instanceof CompletionException || cause instanceof ExecutionException) - && cause.getCause() != null) { - cause = cause.getCause(); - } - return cause instanceof io.lettuce.core.RedisNoScriptException; - } - - private static Reply replyOf(List reply) { - if (reply == null || reply.size() < 6) { - throw new IllegalStateException("the idempotency program answered with an unexpected shape"); - } - return new Reply( - text(reply.get(0)), - number(reply.get(1)), - number(reply.get(2)), - text(reply.get(3)), - text(reply.get(4)), - text(reply.get(5))); - } - - private static long number(Object value) { - if (value instanceof Number n) { - return n.longValue(); - } - String text = text(value); - return text.isBlank() ? 0L : Long.parseLong(text.strip()); - } - - private static String text(Object value) { - if (value instanceof byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - return value == null ? "" : String.valueOf(value); } /** * One program's answer. * - * @param status the transition verdict + * @param status the transition verdict, or the record's state for an inspection * @param attempt the record's attempt counter * @param revision the record's state revision after the call * @param owner the stored owner token @@ -309,5 +269,22 @@ public final class IdempotencyScripts { * @param detail verdict-specific detail: a lease deadline, a TTL, or the observed state */ record Reply( - String status, long attempt, long revision, String owner, String payload, String detail) {} + ScriptStatus status, + long attempt, + long revision, + String owner, + String payload, + String detail) { + + static Reply of(List reply) { + RegisteredLuaScript.requireShape(reply, 6, "idempotency"); + return new Reply( + ScriptStatus.of(RegisteredLuaScript.text(reply.get(0))), + RegisteredLuaScript.number(reply.get(1)), + RegisteredLuaScript.number(reply.get(2)), + RegisteredLuaScript.text(reply.get(3)), + RegisteredLuaScript.text(reply.get(4)), + RegisteredLuaScript.text(reply.get(5))); + } + } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index 52bb09ba..a57aa348 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -1,12 +1,11 @@ package dev.caskeleton.adapter.outbound.cache.redis.idempotency; -import dev.caskeleton.adapter.outbound.cache.redis.RedisSemanticFailureLogger; +import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall; +import dev.caskeleton.adapter.outbound.cache.redis.idempotency.IdempotencyScripts.ScriptStatus; import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; @@ -30,9 +29,10 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; /** * The owner-safe request-replay store, on Redis. @@ -57,7 +57,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort private static final SecureRandom RANDOM = new SecureRandom(); - private final RedisRuntimeOwner owner; + private final SemanticRedisCall call; private final IdempotencyKeys keys; @@ -65,8 +65,6 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort private final Clock clock; - private final Duration commandTimeout; - /** * Creates the adapter. * @@ -82,12 +80,15 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort IdempotencyScripts scripts, Clock clock, Duration commandTimeout) { - this.owner = Objects.requireNonNull(owner, "runtime owner must be non-null"); + this.call = + new SemanticRedisCall( + owner, + RedisConnectionKind.SCRIPT, + Objects.requireNonNull(commandTimeout, "command timeout must be non-null"), + "idempotency"); this.keys = Objects.requireNonNull(keys, "keys must be non-null"); this.scripts = Objects.requireNonNull(scripts, "scripts must be non-null"); this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - this.commandTimeout = - Objects.requireNonNull(commandTimeout, "command timeout must be non-null"); } @Override @@ -109,61 +110,52 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort public IdempotencyClaimOutcome claim(IdempotencyClaimRequest request) { Objects.requireNonNull(request, "request must be non-null"); Instant now = clock.instant(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - IdempotencyScripts.Reply reply = - scripts - .claim( - lease.gateway(), - keys.recordKey(request.scope()), - List.of( - request.claimAttempt().ownerToken(), - request.claimAttempt().operationId().value(), - request.requestFingerprint().hex(), - request.responseCodecId(), - Integer.toString(request.policyRevision()), - Long.toString(request.processingLeaseTtl().toMillis()), - Long.toString(request.replayTtl().toMillis()))) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return claimOutcomeOf(request, reply, now); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return new IdempotencyClaimOutcome.Indeterminate(request.claimAttempt().operationId()); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("idempotency", "claim", failure); - // A refusal before the script was sent — a saturated or closing lane — claimed nothing, so - // the caller may treat it as unavailable. Only a call that may have run is indeterminate. - return notSent(failure) - ? new IdempotencyClaimOutcome.Unavailable() - : new IdempotencyClaimOutcome.Indeterminate(request.claimAttempt().operationId()); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("idempotency", "claim", failure); - return new IdempotencyClaimOutcome.Indeterminate(request.claimAttempt().operationId()); - } + // A refusal before the script was sent — a saturated or closing lane — claimed nothing, so the + // caller may treat it as unavailable. Only a call that may have run is indeterminate. + return call.effect( + "claim", + session -> + claimOutcomeOf( + request, + session.await( + scripts.claim( + session.commands(), + keys.recordKey(request.scope()), + List.of( + request.claimAttempt().ownerToken(), + request.claimAttempt().operationId().value(), + request.requestFingerprint().hex(), + request.responseCodecId(), + Integer.toString(request.policyRevision()), + Long.toString(request.processingLeaseTtl().toMillis()), + Long.toString(request.replayTtl().toMillis())))), + now), + IdempotencyClaimOutcome.Unavailable::new, + () -> new IdempotencyClaimOutcome.Indeterminate(request.claimAttempt().operationId())); } private IdempotencyClaimOutcome claimOutcomeOf( IdempotencyClaimRequest request, IdempotencyScripts.Reply reply, Instant now) { return switch (reply.status()) { - case "ACQUIRED" -> + case ACQUIRED -> new IdempotencyClaimOutcome.Acquired( ownerOf(request, reply), leaseUntil(reply, now, request)); - case "REPLAYED_ACQUIRE" -> + case REPLAYED_ACQUIRE -> new IdempotencyClaimOutcome.ReplayedAcquire( ownerOf(request, reply), leaseUntil(reply, now, request)); - case "TAKEN_OVER" -> + case TAKEN_OVER -> new IdempotencyClaimOutcome.TakenOverClaimed( ownerOf(request, reply), leaseUntil(reply, now, request)); - case "COMPLETED_REPLAY" -> + case COMPLETED_REPLAY -> new IdempotencyClaimOutcome.CompletedReplay( new StoredResponse(reply.payload()), now.plusMillis(Math.max(1, parseLong(reply.detail())))); - case "IN_PROGRESS" -> + case IN_PROGRESS -> new IdempotencyClaimOutcome.InProgress( Duration.ofMillis(Math.max(1, parseLong(reply.detail()))), reply.attempt()); - case "RECOVERY_REQUIRED" -> new IdempotencyClaimOutcome.RecoveryRequired(reply.attempt()); - case "FINGERPRINT_MISMATCH" -> new IdempotencyClaimOutcome.FingerprintMismatch(); - case "OWNER_OPERATION_CONFLICT" -> new IdempotencyClaimOutcome.OwnerOperationConflict(); + case RECOVERY_REQUIRED -> new IdempotencyClaimOutcome.RecoveryRequired(reply.attempt()); + case FINGERPRINT_MISMATCH -> new IdempotencyClaimOutcome.FingerprintMismatch(); + case OWNER_OPERATION_CONFLICT -> new IdempotencyClaimOutcome.OwnerOperationConflict(); default -> new IdempotencyClaimOutcome.Unavailable(); }; } @@ -174,17 +166,14 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort return transition( ownerHandle, operationId, - "CLAIMED", - "EXECUTING", - "", - "", - "", - IdempotencyStartOutcome.STARTED, - IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, - IdempotencyStartOutcome.ABSENT, - IdempotencyStartOutcome.NOT_OWNER, - IdempotencyStartOutcome.NOT_CLAIMED, - IdempotencyStartOutcome.OPERATION_CONFLICT, + new Transition("CLAIMED", "EXECUTING", "", "", ""), + Map.of( + ScriptStatus.APPLIED, IdempotencyStartOutcome.STARTED, + ScriptStatus.ALREADY, IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, + ScriptStatus.ABSENT, IdempotencyStartOutcome.ABSENT, + ScriptStatus.NOT_OWNER, IdempotencyStartOutcome.NOT_OWNER, + ScriptStatus.WRONG_STATE, IdempotencyStartOutcome.NOT_CLAIMED, + ScriptStatus.OPERATION_CONFLICT, IdempotencyStartOutcome.OPERATION_CONFLICT), IdempotencyStartOutcome.INDETERMINATE, IdempotencyStartOutcome.UNAVAILABLE, IdempotencyStartOutcome::carriesOwner); @@ -197,17 +186,15 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort return transition( ownerHandle, operationId, - "EXECUTING", - "EXECUTING", - "", - Long.toString(processingLeaseTtl.toMillis()), - "", - IdempotencyRenewOutcome.RENEWED, - IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION, - IdempotencyRenewOutcome.ABSENT, - IdempotencyRenewOutcome.NOT_OWNER, - IdempotencyRenewOutcome.NOT_IN_PROGRESS, - IdempotencyRenewOutcome.OPERATION_CONFLICT, + new Transition( + "EXECUTING", "EXECUTING", "", Long.toString(processingLeaseTtl.toMillis()), ""), + Map.of( + ScriptStatus.APPLIED, IdempotencyRenewOutcome.RENEWED, + ScriptStatus.ALREADY, IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION, + ScriptStatus.ABSENT, IdempotencyRenewOutcome.ABSENT, + ScriptStatus.NOT_OWNER, IdempotencyRenewOutcome.NOT_OWNER, + ScriptStatus.WRONG_STATE, IdempotencyRenewOutcome.NOT_IN_PROGRESS, + ScriptStatus.OPERATION_CONFLICT, IdempotencyRenewOutcome.OPERATION_CONFLICT), IdempotencyRenewOutcome.INDETERMINATE, IdempotencyRenewOutcome.UNAVAILABLE, IdempotencyRenewOutcome::carriesOwner); @@ -221,51 +208,40 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort OperationId operationId) { Objects.requireNonNull(response, "response must be non-null"); Objects.requireNonNull(replayTtl, "replay TTL must be non-null"); - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - IdempotencyScripts.Reply reply = - scripts - .transition( - lease.gateway(), - keys.recordKey(ownerHandle.scope()), - List.of( - ownerHandle.ownerToken(), - Long.toString(ownerHandle.stateRevision()), - operationId.value(), - "EXECUTING", - "COMPLETED", - response.payload(), - "", - Long.toString(replayTtl.toMillis()))) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return switch (reply.status()) { - case "APPLIED" -> IdempotencyCompleteOutcome.COMPLETED; - case "ALREADY" -> - // The same owner completing twice. Whether it is the same result decides whether this - // is an idempotent repeat or a contradiction the caller has to see. - reply.payload().equals(response.payload()) - ? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT - : IdempotencyCompleteOutcome.RESPONSE_CONFLICT; - case "ABSENT" -> IdempotencyCompleteOutcome.ABSENT; - case "NOT_OWNER" -> IdempotencyCompleteOutcome.NOT_OWNER; - case "OPERATION_CONFLICT" -> IdempotencyCompleteOutcome.OPERATION_CONFLICT; - case "WRONG_STATE" -> IdempotencyCompleteOutcome.NOT_IN_PROGRESS; - default -> IdempotencyCompleteOutcome.UNAVAILABLE; - }; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return IdempotencyCompleteOutcome.INDETERMINATE; - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("idempotency", "complete", failure); - return notSent(failure) - ? IdempotencyCompleteOutcome.UNAVAILABLE - : IdempotencyCompleteOutcome.INDETERMINATE; - } catch (Exception failure) { - RedisSemanticFailureLogger.report("idempotency", "complete", failure); - // The effect may have been recorded. A caller told INDETERMINATE inspects; one told - // UNAVAILABLE might retry the whole operation and duplicate it. - return IdempotencyCompleteOutcome.INDETERMINATE; - } + return call.effect( + "complete", + session -> { + IdempotencyScripts.Reply reply = + session.await( + scripts.transition( + session.commands(), + keys.recordKey(ownerHandle.scope()), + new Transition( + "EXECUTING", + "COMPLETED", + response.payload(), + "", + Long.toString(replayTtl.toMillis())) + .arguments(ownerHandle, operationId))); + return switch (reply.status()) { + case APPLIED -> IdempotencyCompleteOutcome.COMPLETED; + case ALREADY -> + // The same owner completing twice. Whether it is the same result decides whether + // this is an idempotent repeat or a contradiction the caller has to see. + reply.payload().equals(response.payload()) + ? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT + : IdempotencyCompleteOutcome.RESPONSE_CONFLICT; + case ABSENT -> IdempotencyCompleteOutcome.ABSENT; + case NOT_OWNER -> IdempotencyCompleteOutcome.NOT_OWNER; + case OPERATION_CONFLICT -> IdempotencyCompleteOutcome.OPERATION_CONFLICT; + case WRONG_STATE -> IdempotencyCompleteOutcome.NOT_IN_PROGRESS; + default -> IdempotencyCompleteOutcome.UNAVAILABLE; + }; + }, + () -> IdempotencyCompleteOutcome.UNAVAILABLE, + // The effect may have been recorded. A caller told INDETERMINATE inspects; one told + // UNAVAILABLE might retry the whole operation and duplicate it. + () -> IdempotencyCompleteOutcome.INDETERMINATE); } @Override @@ -280,122 +256,98 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort // whether anybody may retry. NO_EFFECT_RETRYABLE releases the operation for another attempt; // EFFECT_UNKNOWN_ABANDONED does not, because retrying an unknown effect is how it happens // twice. - String target = - disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE - ? "FAILED_RETRYABLE" - : "ABANDONED"; - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - IdempotencyScripts.Reply reply = - scripts - .transition( - lease.gateway(), - keys.recordKey(ownerHandle.scope()), - List.of( - ownerHandle.ownerToken(), - Long.toString(ownerHandle.stateRevision()), - operationId.value(), - "EXECUTING", - target, - "", - "", - Long.toString(retention.toMillis()))) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return switch (reply.status()) { - case "APPLIED" -> - disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE - ? IdempotencyFailOutcome.MARKED_RETRYABLE - : IdempotencyFailOutcome.MARKED_ABANDONED; - case "ALREADY" -> IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; - case "ABSENT" -> IdempotencyFailOutcome.ABSENT; - case "NOT_OWNER" -> IdempotencyFailOutcome.NOT_OWNER; - case "OPERATION_CONFLICT" -> IdempotencyFailOutcome.OPERATION_CONFLICT; - case "WRONG_STATE" -> IdempotencyFailOutcome.NOT_IN_PROGRESS; - default -> IdempotencyFailOutcome.UNAVAILABLE; - }; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return IdempotencyFailOutcome.INDETERMINATE; - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("idempotency", "mark-failed", failure); - return notSent(failure) - ? IdempotencyFailOutcome.UNAVAILABLE - : IdempotencyFailOutcome.INDETERMINATE; - } catch (Exception failure) { - RedisSemanticFailureLogger.report("idempotency", "mark-failed", failure); - return IdempotencyFailOutcome.INDETERMINATE; - } + boolean retryable = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE; + Transition transition = + new Transition( + "EXECUTING", + retryable ? "FAILED_RETRYABLE" : "ABANDONED", + "", + "", + Long.toString(retention.toMillis())); + return call.effect( + "mark-failed", + session -> { + IdempotencyScripts.Reply reply = + session.await( + scripts.transition( + session.commands(), + keys.recordKey(ownerHandle.scope()), + transition.arguments(ownerHandle, operationId))); + return switch (reply.status()) { + case APPLIED -> + retryable + ? IdempotencyFailOutcome.MARKED_RETRYABLE + : IdempotencyFailOutcome.MARKED_ABANDONED; + case ALREADY -> IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; + case ABSENT -> IdempotencyFailOutcome.ABSENT; + case NOT_OWNER -> IdempotencyFailOutcome.NOT_OWNER; + case OPERATION_CONFLICT -> IdempotencyFailOutcome.OPERATION_CONFLICT; + case WRONG_STATE -> IdempotencyFailOutcome.NOT_IN_PROGRESS; + default -> IdempotencyFailOutcome.UNAVAILABLE; + }; + }, + () -> IdempotencyFailOutcome.UNAVAILABLE, + () -> IdempotencyFailOutcome.INDETERMINATE); } @Override public IdempotencyReleaseOutcome releaseBeforeExecution( IdempotencyOwner ownerHandle, OperationId operationId) { - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - IdempotencyScripts.Reply reply = - scripts - .release( - lease.gateway(), - keys.recordKey(ownerHandle.scope()), - List.of( - ownerHandle.ownerToken(), - Long.toString(ownerHandle.stateRevision()), - operationId.value())) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return switch (reply.status()) { - case "APPLIED" -> IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION; - case "ABSENT" -> IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; - case "NOT_OWNER" -> IdempotencyReleaseOutcome.NOT_OWNER; - case "OPERATION_CONFLICT" -> IdempotencyReleaseOutcome.OPERATION_CONFLICT; - case "WRONG_STATE" -> IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED; - default -> IdempotencyReleaseOutcome.UNAVAILABLE; - }; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return IdempotencyReleaseOutcome.INDETERMINATE; - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("idempotency", "release-before-execution", failure); - return notSent(failure) - ? IdempotencyReleaseOutcome.UNAVAILABLE - : IdempotencyReleaseOutcome.INDETERMINATE; - } catch (Exception failure) { - RedisSemanticFailureLogger.report("idempotency", "release-before-execution", failure); - return IdempotencyReleaseOutcome.INDETERMINATE; - } + return call.effect( + "release-before-execution", + session -> { + IdempotencyScripts.Reply reply = + session.await( + scripts.release( + session.commands(), + keys.recordKey(ownerHandle.scope()), + List.of( + ownerHandle.ownerToken(), + Long.toString(ownerHandle.stateRevision()), + operationId.value()))); + return switch (reply.status()) { + case APPLIED -> IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION; + case ABSENT -> IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; + case NOT_OWNER -> IdempotencyReleaseOutcome.NOT_OWNER; + case OPERATION_CONFLICT -> IdempotencyReleaseOutcome.OPERATION_CONFLICT; + case WRONG_STATE -> IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED; + default -> IdempotencyReleaseOutcome.UNAVAILABLE; + }; + }, + () -> IdempotencyReleaseOutcome.UNAVAILABLE, + () -> IdempotencyReleaseOutcome.INDETERMINATE); } @Override public IdempotencyInspection inspect(IdempotencyInspectionRequest request) { Objects.requireNonNull(request, "request must be non-null"); Instant now = clock.instant(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - IdempotencyScripts.Reply reply = - scripts - .inspect( - lease.gateway(), - keys.recordKey(request.scope()), - List.of( - request.claimAttempt().ownerToken(), - request.requestFingerprint().hex(), - request.claimAttempt().operationId().value())) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return inspectionOf(request, reply, now); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("idempotency", "inspect", failure); - return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE); - } + // A read: whether or not it reached the server, it changed nothing, so every failure is the + // same "unavailable". + return call.effect( + "inspect", + session -> + inspectionOf( + request, + session.await( + scripts.inspect( + session.commands(), + keys.recordKey(request.scope()), + List.of( + request.claimAttempt().ownerToken(), + request.requestFingerprint().hex(), + request.claimAttempt().operationId().value()))), + now), + () -> IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE), + () -> IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE)); } private IdempotencyInspection inspectionOf( IdempotencyInspectionRequest request, IdempotencyScripts.Reply reply, Instant now) { - if ("ABSENT".equals(reply.status())) { + if (reply.status() == ScriptStatus.ABSENT) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.ABSENT); } - if ("FINGERPRINT_MISMATCH".equals(reply.status())) { + if (reply.status() == ScriptStatus.FINGERPRINT_MISMATCH) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } String[] detail = reply.detail().split("\\|", 2); @@ -412,17 +364,17 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort reply.revision(), request.claimAttempt().operationId()); return switch (reply.status()) { - case "COMPLETED" -> + case COMPLETED -> new IdempotencyInspection( IdempotencyInspectionOutcome.COMPLETED_REPLAY, Optional.empty(), Optional.empty(), Optional.of(new StoredResponse(reply.payload())), Optional.of(now.plusMillis(Math.max(1, ttlMillis)))); - case "FAILED_RETRYABLE" -> + case FAILED_RETRYABLE -> IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FAILED_RETRYABLE); - case "ABANDONED" -> IdempotencyInspection.outcome(IdempotencyInspectionOutcome.ABANDONED); - case "CLAIMED" -> + case ABANDONED -> IdempotencyInspection.outcome(IdempotencyInspectionOutcome.ABANDONED); + case CLAIMED -> "MINE".equals(ownership) ? new IdempotencyInspection( IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION, @@ -431,7 +383,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort Optional.empty(), Optional.empty()) : IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER); - case "EXECUTING" -> + case EXECUTING -> "MINE".equals(ownership) ? new IdempotencyInspection( IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, @@ -444,77 +396,63 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort }; } - private > IdempotencyMutationResult transition( - IdempotencyOwner ownerHandle, - OperationId operationId, - String fromState, - String toState, - String payload, - String leaseUntil, - String ttlMillis, - O applied, - O already, - O absent, - O notOwner, - O wrongState, - O operationConflict, - O indeterminate, - O unavailable, - java.util.function.Predicate carriesOwner) { - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - IdempotencyScripts.Reply reply = - scripts - .transition( - lease.gateway(), - keys.recordKey(ownerHandle.scope()), - List.of( - ownerHandle.ownerToken(), - Long.toString(ownerHandle.stateRevision()), - operationId.value(), - fromState, - toState, - payload, - leaseUntil, - ttlMillis)) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - O outcome = - switch (reply.status()) { - case "APPLIED" -> applied; - case "ALREADY" -> already; - case "ABSENT" -> absent; - case "NOT_OWNER" -> notOwner; - case "OPERATION_CONFLICT" -> operationConflict; - case "WRONG_STATE" -> wrongState; - default -> indeterminate; - }; - return new IdempotencyMutationResult<>( - outcome, - carriesOwner.test(outcome) - ? new IdempotencyOwner( - ownerHandle.scope(), - ownerHandle.ownerToken(), - reply.attempt(), - reply.revision(), - ownerHandle.claimOperationId()) - : null, - carriesOwner); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return new IdempotencyMutationResult<>(indeterminate, null, carriesOwner); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("idempotency", "transition", failure); - return new IdempotencyMutationResult<>( - notSent(failure) ? unavailable : indeterminate, null, carriesOwner); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("idempotency", "transition", failure); - return new IdempotencyMutationResult<>(indeterminate, null, carriesOwner); + /** + * One owner+revision compare-and-set, as the transition program takes it. + * + * @param fromState the state the record must be in + * @param toState the state it moves to + * @param payload the response to store, empty for none + * @param leaseMillis a new processing lease, empty to keep the current one + * @param ttlMillis a new record TTL, empty to keep the current one + */ + private record Transition( + String fromState, String toState, String payload, String leaseMillis, String ttlMillis) { + + List arguments(IdempotencyOwner ownerHandle, OperationId operationId) { + return List.of( + ownerHandle.ownerToken(), + Long.toString(ownerHandle.stateRevision()), + operationId.value(), + fromState, + toState, + payload, + leaseMillis, + ttlMillis); } } - /** A typed runtime refusal raised before any command existed — nothing reached Redis. */ - private static boolean notSent(RedisOperationException failure) { - return !failure.metadata().ambiguousExecution(); + private > IdempotencyMutationResult transition( + IdempotencyOwner ownerHandle, + OperationId operationId, + Transition transition, + Map outcomes, + O indeterminate, + O unavailable, + Predicate carriesOwner) { + return call.effect( + "transition", + session -> { + IdempotencyScripts.Reply reply = + session.await( + scripts.transition( + session.commands(), + keys.recordKey(ownerHandle.scope()), + transition.arguments(ownerHandle, operationId))); + O outcome = outcomes.getOrDefault(reply.status(), indeterminate); + return new IdempotencyMutationResult<>( + outcome, + carriesOwner.test(outcome) + ? new IdempotencyOwner( + ownerHandle.scope(), + ownerHandle.ownerToken(), + reply.attempt(), + reply.revision(), + ownerHandle.claimOperationId()) + : null, + carriesOwner); + }, + () -> new IdempotencyMutationResult<>(unavailable, null, carriesOwner), + () -> new IdempotencyMutationResult<>(indeterminate, null, carriesOwner)); } private static IdempotencyOwner ownerOf( diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/keyspace/CapabilityKeyspace.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/keyspace/CapabilityKeyspace.java index 564bc94d..0e0cc205 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/keyspace/CapabilityKeyspace.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/keyspace/CapabilityKeyspace.java @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.keyspace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.nio.charset.StandardCharsets; import java.util.Objects; diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScripts.java index 50ff698e..4dba8f90 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScripts.java @@ -1,13 +1,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.lease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.RegisteredLuaScript; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; /** * The four owner-checked lease programs. @@ -80,107 +77,27 @@ public final class LeaseScripts { return {1, redis.call('PTTL', KEYS[1]), existing} """; - private final AtomicReference acquireDigest = new AtomicReference<>(); - private final AtomicReference renewDigest = new AtomicReference<>(); - private final AtomicReference releaseDigest = new AtomicReference<>(); - private final AtomicReference inspectDigest = new AtomicReference<>(); + private final RegisteredLuaScript acquire = new RegisteredLuaScript(ACQUIRE); + private final RegisteredLuaScript renew = new RegisteredLuaScript(RENEW); + private final RegisteredLuaScript release = new RegisteredLuaScript(RELEASE); + private final RegisteredLuaScript inspect = new RegisteredLuaScript(INSPECT); CompletionStage acquire( - RedisCommandGateway gateway, byte[] key, String ownership, long ttlMillis) { - return run(gateway, ACQUIRE, acquireDigest, key, args(ownership, ttlMillis)); + SemanticRedisCommands commands, byte[] key, String ownership, long ttlMillis) { + return acquire.evaluateForList(commands, key, args(ownership, ttlMillis)).thenApply(Reply::of); } CompletionStage renew( - RedisCommandGateway gateway, byte[] key, String ownership, long ttlMillis) { - return run(gateway, RENEW, renewDigest, key, args(ownership, ttlMillis)); + SemanticRedisCommands commands, byte[] key, String ownership, long ttlMillis) { + return renew.evaluateForList(commands, key, args(ownership, ttlMillis)).thenApply(Reply::of); } - CompletionStage release(RedisCommandGateway gateway, byte[] key, String ownership) { - return run(gateway, RELEASE, releaseDigest, key, args(ownership, 0)); + CompletionStage release(SemanticRedisCommands commands, byte[] key, String ownership) { + return release.evaluateForList(commands, key, args(ownership, 0)).thenApply(Reply::of); } - CompletionStage inspect(RedisCommandGateway gateway, byte[] key, String ownership) { - return run(gateway, INSPECT, inspectDigest, key, args(ownership, 0)); - } - - private CompletionStage run( - RedisCommandGateway gateway, - String source, - AtomicReference cache, - byte[] key, - List arguments) { - return digest(gateway, source, cache) - .thenCompose(digest -> gateway.evaluateRegisteredForList(digest, key, arguments)) - .handle( - (reply, failure) -> - failure == null - ? CompletableFuture.completedFuture(reply) - : reload(gateway, source, cache, key, arguments, failure)) - .thenCompose(stage -> stage) - .thenApply(LeaseScripts::replyOf); - } - - private CompletionStage> reload( - RedisCommandGateway gateway, - String source, - AtomicReference cache, - byte[] key, - List arguments, - Throwable failure) { - if (!scriptMissing(failure)) { - return CompletableFuture.failedFuture(failure); - } - cache.set(null); - return digest(gateway, source, cache) - .thenCompose(digest -> gateway.evaluateRegisteredForList(digest, key, arguments)); - } - - private static CompletionStage digest( - RedisCommandGateway gateway, String source, AtomicReference cache) { - String cached = cache.get(); - if (cached != null) { - return CompletableFuture.completedFuture(cached); - } - return gateway - .loadScript(source.getBytes(StandardCharsets.UTF_8)) - .thenApply( - loaded -> { - cache.set(loaded); - return loaded; - }); - } - - private static boolean scriptMissing(Throwable failure) { - Throwable cause = failure; - while ((cause instanceof CompletionException || cause instanceof ExecutionException) - && cause.getCause() != null) { - cause = cause.getCause(); - } - return cause instanceof io.lettuce.core.RedisNoScriptException; - } - - private static Reply replyOf(List reply) { - if (reply == null || reply.size() < 3) { - throw new IllegalStateException("the lease program answered with an unexpected shape"); - } - return new Reply(asLong(reply.get(0)), asLong(reply.get(1)), asText(reply.get(2))); - } - - private static long asLong(Object value) { - if (value instanceof Number number) { - return number.longValue(); - } - if (value instanceof byte[] bytes) { - return Long.parseLong(new String(bytes, StandardCharsets.UTF_8).strip()); - } - throw new IllegalStateException("the lease program answered with an unexpected value type"); - } - - private static String asText(Object value) { - if (value instanceof byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - return value == null ? "" : String.valueOf(value); + CompletionStage inspect(SemanticRedisCommands commands, byte[] key, String ownership) { + return inspect.evaluateForList(commands, key, args(ownership, 0)).thenApply(Reply::of); } private static List args(String ownership, long ttlMillis) { @@ -197,5 +114,14 @@ public final class LeaseScripts { * @param remainingMillis the server's remaining TTL, diagnostic only * @param holder the stored ownership string, empty when absent */ - record Reply(long status, long remainingMillis, String holder) {} + record Reply(long status, long remainingMillis, String holder) { + + static Reply of(List reply) { + RegisteredLuaScript.requireShape(reply, 3, "lease"); + return new Reply( + RegisteredLuaScript.number(reply.get(0)), + RegisteredLuaScript.number(reply.get(1)), + RegisteredLuaScript.text(reply.get(2))); + } + } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapter.java index 2c472527..fd421ef9 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapter.java @@ -1,12 +1,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.lease; -import dev.caskeleton.adapter.outbound.cache.redis.RedisSemanticFailureLogger; +import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall; import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.application.lease.DistributedLeasePort; import dev.caskeleton.application.lease.LeaseAcquireOutcome; import dev.caskeleton.application.lease.LeaseAttempt; @@ -24,7 +22,6 @@ import java.time.Duration; import java.time.Instant; import java.util.Base64; import java.util.Objects; -import java.util.concurrent.TimeUnit; import java.util.function.LongSupplier; /** @@ -47,7 +44,7 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort private static final SecureRandom RANDOM = new SecureRandom(); - private final RedisRuntimeOwner owner; + private final SemanticRedisCall call; private final LeaseKeys keys; @@ -57,8 +54,6 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort private final LongSupplier nanoTime; - private final Duration commandTimeout; - private final Duration contentionRetryAfter; private final Duration driftBudget; @@ -84,13 +79,16 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort Duration commandTimeout, Duration contentionRetryAfter, Duration driftBudget) { - this.owner = Objects.requireNonNull(owner, "runtime owner must be non-null"); + this.call = + new SemanticRedisCall( + owner, + RedisConnectionKind.SCRIPT, + Objects.requireNonNull(commandTimeout, "command timeout must be non-null"), + "lease"); this.keys = Objects.requireNonNull(keys, "keys must be non-null"); this.scripts = Objects.requireNonNull(scripts, "scripts must be non-null"); this.clock = Objects.requireNonNull(clock, "clock must be non-null"); this.nanoTime = Objects.requireNonNull(nanoTime, "monotonic source must be non-null"); - this.commandTimeout = - Objects.requireNonNull(commandTimeout, "command timeout must be non-null"); this.contentionRetryAfter = Objects.requireNonNull(contentionRetryAfter, "contention retry-after must be non-null"); this.driftBudget = Objects.requireNonNull(driftBudget, "drift budget must be non-null"); @@ -148,43 +146,39 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort Duration validity = localValidityOf(request.leaseTtl()); String ownership = ownershipOf(request.attempt()); long startedAt = nanoTime.getAsLong(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - LeaseScripts.Reply reply = - scripts - .acquire( - lease.gateway(), - keys.leaseKey(request.purpose(), request.resourceDigest()), - ownership, - request.leaseTtl().toMillis()) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return switch ((int) reply.status()) { - case 1 -> new LeaseAcquireOutcome.Acquired(handle(request, ownership, validity, startedAt)); - case 2 -> - // The same owner and operation already hold it. This is a retry whose first reply was - // lost, not a second acquisition, and answering "contended" would make a caller back - // off from a lease it already owns. The server did not re-grant the TTL, so the - // handle gets what is left of it, not a fresh one. - new LeaseAcquireOutcome.ReplayedSameOperation( - handle(request, ownership, observedValidityOf(reply.remainingMillis()), startedAt)); - default -> contendedOrConflicting(request, reply); - }; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return new LeaseAcquireOutcome.Indeterminate(request.attempt().operationId()); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("lease", "acquire", failure); - // Refused before anything was sent: nothing can have been taken. - return notSent(failure) - ? new LeaseAcquireOutcome.Unavailable(LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND) - : new LeaseAcquireOutcome.Indeterminate(request.attempt().operationId()); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("lease", "acquire", failure); - // An acquire whose outcome is unknown may have taken the lease. Reporting it as a clean - // failure would let the caller retry under a new attempt and hold it twice; Indeterminate - // tells them to inspect with the same attempt instead. - return new LeaseAcquireOutcome.Indeterminate(request.attempt().operationId()); - } + return call.effect( + "acquire", + session -> { + LeaseScripts.Reply reply = + session.await( + scripts.acquire( + session.commands(), + keys.leaseKey(request.purpose(), request.resourceDigest()), + ownership, + request.leaseTtl().toMillis())); + return switch ((int) reply.status()) { + case 1 -> + new LeaseAcquireOutcome.Acquired(handle(request, ownership, validity, startedAt)); + case 2 -> + // The same owner and operation already hold it. This is a retry whose first reply + // was lost, not a second acquisition, and answering "contended" would make a caller + // back off from a lease it already owns. The server did not re-grant the TTL, so + // the handle gets what is left of it, not a fresh one. + new LeaseAcquireOutcome.ReplayedSameOperation( + handle( + request, + ownership, + observedValidityOf(reply.remainingMillis()), + startedAt)); + default -> contendedOrConflicting(request, reply); + }; + }, + // Refused before anything was sent: nothing can have been taken. + () -> new LeaseAcquireOutcome.Unavailable(LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND), + // An acquire whose outcome is unknown may have taken the lease. Reporting it as a clean + // failure would let the caller retry under a new attempt and hold it twice; Indeterminate + // tells them to inspect with the same attempt instead. + () -> new LeaseAcquireOutcome.Indeterminate(request.attempt().operationId())); } private LeaseAcquireOutcome contendedOrConflicting( @@ -208,43 +202,36 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort Objects.requireNonNull(request, "request must be non-null"); String ownership = ownershipOf(request.attempt()); long startedAt = nanoTime.getAsLong(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - LeaseScripts.Reply reply = - scripts - .inspect( - lease.gateway(), - keys.leaseKey(request.purpose(), request.resourceDigest()), - ownership) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - if (reply.status() == 1) { - return new LeaseInspectionOutcome.Owned( - new RedisLeaseHandle( - request.purpose(), - request.resourceDigest(), - request.attempt(), - ownership, - observedValidityOf(reply.remainingMillis()), - startedAt)); - } - if (reply.status() == 0) { - return new LeaseInspectionOutcome.Absent(); - } - return reply.holder().startsWith(request.attempt().ownerToken() + ":") - ? new LeaseInspectionOutcome.OwnerOperationConflict() - : new LeaseInspectionOutcome.NotOwner(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return new LeaseInspectionOutcome.Indeterminate(request.attempt().operationId()); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("lease", "inspect", failure); - return notSent(failure) - ? new LeaseInspectionOutcome.Unavailable(LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND) - : new LeaseInspectionOutcome.Indeterminate(request.attempt().operationId()); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("lease", "inspect", failure); - return new LeaseInspectionOutcome.Indeterminate(request.attempt().operationId()); - } + return call.effect( + "inspect", + session -> { + LeaseScripts.Reply reply = + session.await( + scripts.inspect( + session.commands(), + keys.leaseKey(request.purpose(), request.resourceDigest()), + ownership)); + if (reply.status() == 1) { + return new LeaseInspectionOutcome.Owned( + new RedisLeaseHandle( + request.purpose(), + request.resourceDigest(), + request.attempt(), + ownership, + observedValidityOf(reply.remainingMillis()), + startedAt)); + } + if (reply.status() == 0) { + return new LeaseInspectionOutcome.Absent(); + } + return reply.holder().startsWith(request.attempt().ownerToken() + ":") + ? new LeaseInspectionOutcome.OwnerOperationConflict() + : new LeaseInspectionOutcome.NotOwner(); + }, + () -> + new LeaseInspectionOutcome.Unavailable( + LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND), + () -> new LeaseInspectionOutcome.Indeterminate(request.attempt().operationId())); } private RedisLeaseHandle handle( @@ -262,11 +249,6 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort return attempt.ownerToken() + ":" + attempt.operationId(); } - /** A typed runtime refusal raised before any command existed — nothing reached Redis. */ - private static boolean notSent(RedisOperationException failure) { - return !failure.metadata().ambiguousExecution(); - } - /** A held lease, whose validity is its own to track. */ private final class RedisLeaseHandle implements LeaseHandle { @@ -340,85 +322,65 @@ public final class RedisDistributedLeaseAdapter implements DistributedLeasePort // Before the round trip, for the reason tryAcquire gives. Duration validity = localValidityOf(leaseTtl); long startedAt = nanoTime.getAsLong(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - LeaseScripts.Reply reply = - scripts - .renew( - lease.gateway(), - keys.leaseKey(purpose, resourceDigest), - ownership, - leaseTtl.toMillis()) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - if (reply.status() == 1) { - // The renewed budget is shortened by the drift allowance for the same reason the first - // one was: a renew does not make the two clocks agree. - grantedValidity = validity; - grantedAtNanos = startedAt; - return new LeaseRenewOutcome.Renewed(remainingValidity()); - } - state = LeaseState.LOST; - return reply.status() == 0 - ? new LeaseRenewOutcome.Absent() - : new LeaseRenewOutcome.NotOwner(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - state = LeaseState.UNKNOWN; - return new LeaseRenewOutcome.Indeterminate(attempt.operationId()); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("lease", "renew", failure); - if (notSent(failure)) { + return call.effect( + "renew", + session -> { + LeaseScripts.Reply reply = + session.await( + scripts.renew( + session.commands(), + keys.leaseKey(purpose, resourceDigest), + ownership, + leaseTtl.toMillis())); + if (reply.status() == 1) { + // The renewed budget is shortened by the drift allowance for the same reason the + // first one was: a renew does not make the two clocks agree. + grantedValidity = validity; + grantedAtNanos = startedAt; + return new LeaseRenewOutcome.Renewed(remainingValidity()); + } + state = LeaseState.LOST; + return reply.status() == 0 + ? new LeaseRenewOutcome.Absent() + : new LeaseRenewOutcome.NotOwner(); + }, // Nothing reached the server, so the lease is exactly what it was: still held, on the // budget it already had. - return new LeaseRenewOutcome.Unavailable( - LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND); - } - state = LeaseState.UNKNOWN; - return new LeaseRenewOutcome.Indeterminate(attempt.operationId()); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("lease", "renew", failure); - // A renew whose outcome is unknown must not extend the local budget. Leaving the handle in - // UNKNOWN is what keeps a caller from acting on validity it cannot demonstrate. - state = LeaseState.UNKNOWN; - return new LeaseRenewOutcome.Indeterminate(attempt.operationId()); - } + () -> new LeaseRenewOutcome.Unavailable(LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND), + () -> { + // A renew whose outcome is unknown must not extend the local budget. Leaving the handle + // in UNKNOWN is what keeps a caller from acting on validity it cannot demonstrate. + state = LeaseState.UNKNOWN; + return new LeaseRenewOutcome.Indeterminate(attempt.operationId()); + }); } @Override public LeaseReleaseOutcome release() { - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - LeaseScripts.Reply reply = - scripts - .release(lease.gateway(), keys.leaseKey(purpose, resourceDigest), ownership) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - if (reply.status() == 1) { - state = LeaseState.RELEASED; - return new LeaseReleaseOutcome.Released(); - } - if (reply.status() == 0) { - state = LeaseState.RELEASED; - return new LeaseReleaseOutcome.AlreadyAbsent(); - } - state = LeaseState.LOST; - return new LeaseReleaseOutcome.NotOwner(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - state = LeaseState.UNKNOWN; - return new LeaseReleaseOutcome.Indeterminate(attempt.operationId()); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("lease", "release", failure); - if (notSent(failure)) { - return new LeaseReleaseOutcome.Unavailable( - LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND); - } - state = LeaseState.UNKNOWN; - return new LeaseReleaseOutcome.Indeterminate(attempt.operationId()); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("lease", "release", failure); - state = LeaseState.UNKNOWN; - return new LeaseReleaseOutcome.Indeterminate(attempt.operationId()); - } + return call.effect( + "release", + session -> { + LeaseScripts.Reply reply = + session.await( + scripts.release( + session.commands(), keys.leaseKey(purpose, resourceDigest), ownership)); + if (reply.status() == 1) { + state = LeaseState.RELEASED; + return new LeaseReleaseOutcome.Released(); + } + if (reply.status() == 0) { + state = LeaseState.RELEASED; + return new LeaseReleaseOutcome.AlreadyAbsent(); + } + state = LeaseState.LOST; + return new LeaseReleaseOutcome.NotOwner(); + }, + () -> + new LeaseReleaseOutcome.Unavailable(LeaseUnavailableCategory.UNAVAILABLE_BEFORE_SEND), + () -> { + state = LeaseState.UNKNOWN; + return new LeaseReleaseOutcome.Indeterminate(attempt.operationId()); + }); } } diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitAlgorithm.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitAlgorithm.java similarity index 57% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitAlgorithm.java rename to src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitAlgorithm.java index a2faaf1d..34710a4d 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitAlgorithm.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitAlgorithm.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.ratelimit; +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; public enum RateLimitAlgorithm { FIXED_WINDOW, diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitEvaluationDedupPolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java similarity index 93% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitEvaluationDedupPolicy.java rename to src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java index 9c171e80..212b2826 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitEvaluationDedupPolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.ratelimit; +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; import java.time.Duration; import java.util.Objects; @@ -27,7 +27,7 @@ public record RateLimitEvaluationDedupPolicy( "disabled evaluation dedup must not allocate TTL, entries, or stored bytes"); } } else { - RateLimitBounds.positiveDuration(timeToLive, "timeToLive", MAXIMUM_TIME_TO_LIVE); + RateLimitPolicyBounds.positiveDuration(timeToLive, "timeToLive", MAXIMUM_TIME_TO_LIVE); if (maximumEntries < 1 || maximumEntries > MAXIMUM_ENTRIES) { throw new IllegalArgumentException("maximumEntries must be in 1.." + MAXIMUM_ENTRIES); } diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitFailurePolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitFailurePolicy.java similarity index 67% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitFailurePolicy.java rename to src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitFailurePolicy.java index 9fd155b6..2e5c492a 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitFailurePolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitFailurePolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.ratelimit; +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; /** V1 deliberately does not claim fail-open or local fallback semantics. */ public enum RateLimitFailurePolicy { diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitKeys.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitKeys.java index 7ffbe5e7..53a5c961 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitKeys.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitKeys.java @@ -1,8 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.shared.ratelimit.RateLimitPolicy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.util.Objects; /** diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitPolicy.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java similarity index 92% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitPolicy.java rename to src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java index 57b7a945..413c9b26 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitPolicy.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicy.java @@ -1,5 +1,6 @@ -package dev.caskeleton.shared.ratelimit; +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; +import dev.caskeleton.shared.ratelimit.RateParameters; import java.time.Duration; import java.util.Objects; @@ -36,18 +37,20 @@ public record RateLimitPolicy( } public RateLimitPolicy { - RateLimitBounds.policyId(policyId); - RateLimitBounds.policyRevision(policyRevision); + RateLimitPolicyBounds.policyId(policyId); + RateLimitPolicyBounds.policyRevision(policyRevision); Objects.requireNonNull(algorithm, "algorithm must not be null"); Objects.requireNonNull(parameters, "parameters must not be null"); if (maximumCost <= 0 || maximumCost > RateParameters.MAXIMUM_EXACT_INTEGER) { throw new IllegalArgumentException( "maximumCost must be positive and within Lua's exact integer range"); } - RateLimitBounds.positiveDuration( - cleanupGrace, "cleanupGrace", RateLimitBounds.MAXIMUM_CLEANUP_GRACE); - RateLimitBounds.nonNegativeDuration( - maximumClockRegression, "maximumClockRegression", RateLimitBounds.MAXIMUM_CLOCK_REGRESSION); + RateLimitPolicyBounds.positiveDuration( + cleanupGrace, "cleanupGrace", RateLimitPolicyBounds.MAXIMUM_CLEANUP_GRACE); + RateLimitPolicyBounds.nonNegativeDuration( + maximumClockRegression, + "maximumClockRegression", + RateLimitPolicyBounds.MAXIMUM_CLOCK_REGRESSION); Objects.requireNonNull(failurePolicy, "failurePolicy must not be null"); Objects.requireNonNull(evaluationDedupPolicy, "evaluationDedupPolicy must not be null"); if (failurePolicy != RateLimitFailurePolicy.FAIL_CLOSED) { diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java new file mode 100644 index 00000000..82eb9e90 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyBounds.java @@ -0,0 +1,70 @@ +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; + +import java.time.Duration; +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * The bounds a Redis rate-limit policy is validated against. + * + *

The policy is this adapter's configuration, not a shared contract, so its bounds live with it. + * The identifier grammars match the ones {@code shared-contract} applies to a request, because a + * request names the policy by the same identifier. + */ +final class RateLimitPolicyBounds { + + static final Duration MAXIMUM_CLEANUP_GRACE = Duration.ofDays(1); + static final Duration MAXIMUM_CLOCK_REGRESSION = Duration.ofHours(1); + + private static final Pattern POLICY_ID = Pattern.compile("[a-z][a-z0-9-]{0,62}"); + private static final Pattern POLICY_REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,63}"); + + private RateLimitPolicyBounds() {} + + static String policyId(String value) { + return boundedIdentifier(value, "policyId", POLICY_ID); + } + + static String policyRevision(String value) { + return boundedIdentifier(value, "policyRevision", POLICY_REVISION); + } + + static Duration positiveDuration(Duration value, String field, Duration maximum) { + return duration(value, field, false, maximum); + } + + static Duration nonNegativeDuration(Duration value, String field, Duration maximum) { + return duration(value, field, true, maximum); + } + + private static String boundedIdentifier(String value, String field, Pattern pattern) { + Objects.requireNonNull(value, field + " must not be null"); + if (!pattern.matcher(value).matches()) { + throw new IllegalArgumentException(field + " has an invalid bounded representation"); + } + return value; + } + + private static Duration duration( + Duration value, String field, boolean zeroAllowed, Duration maximum) { + Objects.requireNonNull(value, field + " must not be null"); + if (value.isNegative() || (!zeroAllowed && value.isZero())) { + throw new IllegalArgumentException( + field + (zeroAllowed ? " must not be negative" : " must be positive")); + } + if (value.compareTo(maximum) > 0) { + throw new IllegalArgumentException(field + " exceeds its maximum duration of " + maximum); + } + long milliseconds; + try { + milliseconds = value.toMillis(); + } catch (ArithmeticException exception) { + throw new IllegalArgumentException( + field + " exceeds the supported milliseconds range", exception); + } + if (!Duration.ofMillis(milliseconds).equals(value)) { + throw new IllegalArgumentException(field + " must use whole milliseconds"); + } + return value; + } +} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitScripts.java index 8f2901f4..f8ebb201 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitScripts.java @@ -1,16 +1,13 @@ package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; -import dev.caskeleton.shared.ratelimit.RateLimitPolicy; +import dev.caskeleton.adapter.outbound.cache.redis.RegisteredLuaScript; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import dev.caskeleton.shared.ratelimit.RateParameters; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; /** * The atomic programs that make one rate-limit decision one round trip. @@ -152,46 +149,43 @@ public final class RateLimitScripts { return {1, math.floor(tokens), resetAfter} """; - private final AtomicReference fixedWindowDigest = new AtomicReference<>(); + private final RegisteredLuaScript fixedWindow = new RegisteredLuaScript(FIXED_WINDOW); - private final AtomicReference slidingCounterDigest = new AtomicReference<>(); + private final RegisteredLuaScript slidingCounter = new RegisteredLuaScript(SLIDING_COUNTER); - private final AtomicReference tokenBucketDigest = new AtomicReference<>(); + private final RegisteredLuaScript tokenBucket = new RegisteredLuaScript(TOKEN_BUCKET); /** * Evaluates one request atomically. * - * @param gateway the driver seam of a borrowed lease + * @param commands the commands of a borrowed SCRIPT lease * @param key the rendered counter key * @param policy the policy to apply * @param cost the request's cost * @return the evaluation */ public CompletionStage evaluate( - RedisCommandGateway gateway, byte[] key, RateLimitPolicy policy, long cost) { - Objects.requireNonNull(gateway, "gateway must be non-null"); + SemanticRedisCommands commands, byte[] key, RateLimitPolicy policy, long cost) { + Objects.requireNonNull(commands, "commands must be non-null"); Objects.requireNonNull(policy, "policy must be non-null"); long stateTtlMillis = stateTtlMillis(policy); return switch (policy.parameters()) { case RateParameters.FixedWindow window -> run( - gateway, - FIXED_WINDOW, - fixedWindowDigest, + fixedWindow, + commands, key, arguments(window.limit(), window.window().toMillis(), cost, stateTtlMillis)); case RateParameters.SlidingCounter sliding -> run( - gateway, - SLIDING_COUNTER, - slidingCounterDigest, + slidingCounter, + commands, key, arguments(sliding.limit(), sliding.window().toMillis(), cost, stateTtlMillis)); case RateParameters.TokenBucket bucket -> run( - gateway, - TOKEN_BUCKET, - tokenBucketDigest, + tokenBucket, + commands, key, arguments( bucket.capacity(), @@ -222,82 +216,22 @@ public final class RateLimitScripts { }; } - private CompletionStage run( - RedisCommandGateway gateway, - String source, - AtomicReference cache, + private static CompletionStage run( + RegisteredLuaScript program, + SemanticRedisCommands commands, byte[] key, List arguments) { - return digest(gateway, source, cache) - .thenCompose(digest -> gateway.evaluateRegisteredForList(digest, key, arguments)) - .handle( - (reply, failure) -> - failure == null - ? CompletableFuture.completedFuture(reply) - : reload(gateway, source, cache, key, arguments, failure)) - .thenCompose(stage -> stage) + return program + .evaluateForList(commands, key, arguments) .thenApply(RateLimitScripts::evaluationOf); } - private CompletionStage> reload( - RedisCommandGateway gateway, - String source, - AtomicReference cache, - byte[] key, - List arguments, - Throwable failure) { - if (!scriptMissing(failure)) { - return CompletableFuture.failedFuture(failure); - } - cache.set(null); - return digest(gateway, source, cache) - .thenCompose(digest -> gateway.evaluateRegisteredForList(digest, key, arguments)); - } - - private static CompletionStage digest( - RedisCommandGateway gateway, String source, AtomicReference cache) { - String cached = cache.get(); - if (cached != null) { - return CompletableFuture.completedFuture(cached); - } - return gateway - .loadScript(source.getBytes(StandardCharsets.UTF_8)) - .thenApply( - loaded -> { - cache.set(loaded); - return loaded; - }); - } - - private static boolean scriptMissing(Throwable failure) { - Throwable cause = failure; - while ((cause instanceof CompletionException || cause instanceof ExecutionException) - && cause.getCause() != null) { - cause = cause.getCause(); - } - return cause instanceof io.lettuce.core.RedisNoScriptException; - } - private static Evaluation evaluationOf(List reply) { - if (reply == null || reply.size() < 3) { - throw new IllegalStateException( - "the rate limit program answered with " - + (reply == null ? "nothing" : reply.size()) - + " values; three were expected"); - } - return new Evaluation(asLong(reply.get(0)) == 1L, asLong(reply.get(1)), asLong(reply.get(2))); - } - - private static long asLong(Object value) { - if (value instanceof Number number) { - return number.longValue(); - } - if (value instanceof byte[] bytes) { - return Long.parseLong(new String(bytes, StandardCharsets.UTF_8).strip()); - } - throw new IllegalStateException( - "the rate limit program answered with an unexpected value type: " - + (value == null ? "null" : value.getClass().getName())); + RegisteredLuaScript.requireShape(reply, 3, "rate limit"); + return new Evaluation( + RegisteredLuaScript.number(reply.get(0)) == 1L, + RegisteredLuaScript.number(reply.get(1)), + RegisteredLuaScript.number(reply.get(2))); } private static List arguments(long... values) { 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 184c6f3e..4599a531 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 @@ -1,14 +1,11 @@ package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; -import dev.caskeleton.adapter.outbound.cache.redis.RedisSemanticFailureLogger; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.SemanticRedisCall; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort; import dev.caskeleton.shared.ratelimit.RateLimitDecision; import dev.caskeleton.shared.ratelimit.RateLimitOutcome; -import dev.caskeleton.shared.ratelimit.RateLimitPolicy; import dev.caskeleton.shared.ratelimit.RateLimitRequest; import dev.caskeleton.shared.ratelimit.RateParameters; import java.time.Clock; @@ -17,7 +14,6 @@ import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.concurrent.TimeUnit; /** * The provider-neutral edge rate limit, on Redis. @@ -38,7 +34,7 @@ import java.util.concurrent.TimeUnit; */ public final class RedisEdgeRateLimitAdapter implements EdgeRateLimitPort { - private final RedisRuntimeOwner owner; + private final SemanticRedisCall call; private final RateLimitKeys keys; @@ -48,8 +44,6 @@ public final class RedisEdgeRateLimitAdapter implements EdgeRateLimitPort { private final Clock clock; - private final Duration commandTimeout; - private final Duration failureRetryAfter; /** @@ -71,13 +65,16 @@ public final class RedisEdgeRateLimitAdapter implements EdgeRateLimitPort { Clock clock, Duration commandTimeout, Duration failureRetryAfter) { - this.owner = Objects.requireNonNull(owner, "runtime owner must be non-null"); + this.call = + new SemanticRedisCall( + owner, + RedisConnectionKind.SCRIPT, + Objects.requireNonNull(commandTimeout, "command timeout must be non-null"), + "rate-limit"); this.keys = Objects.requireNonNull(keys, "keys must be non-null"); this.policies = Map.copyOf(Objects.requireNonNull(policies, "policies must be non-null")); this.scripts = Objects.requireNonNull(scripts, "scripts must be non-null"); this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - this.commandTimeout = - Objects.requireNonNull(commandTimeout, "command timeout must be non-null"); this.failureRetryAfter = Objects.requireNonNull(failureRetryAfter, "failure retry-after must be non-null"); } @@ -106,34 +103,24 @@ public final class RedisEdgeRateLimitAdapter implements EdgeRateLimitPort { RateLimitOutcome.UnavailableCategory.ADMISSION_REJECTED); } - try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { - RateLimitScripts.Evaluation evaluation = - scripts - .evaluate( - lease.gateway(), - keys.counterKey(policy, request.subjectDigest()), - policy, - request.cost()) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return new RateLimitOutcome.Evaluated(decisionOf(policy, evaluation, now)); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return unavailable(policy, RateLimitOutcome.UnavailableCategory.NO_MUTATION_CONFIRMED); - } catch (RedisOperationException failure) { - RedisSemanticFailureLogger.report("rate-limit", "evaluate", failure); - // The distinction that matters: a command the guard refused never reached Redis and consumed - // no budget, while a command 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 unavailable( - policy, - failure.metadata().ambiguousExecution() - ? RateLimitOutcome.UnavailableCategory.NO_MUTATION_CONFIRMED - : RateLimitOutcome.UnavailableCategory.UNAVAILABLE_BEFORE_SEND); - } catch (Exception failure) { - RedisSemanticFailureLogger.report("rate-limit", "evaluate", failure); - return unavailable(policy, RateLimitOutcome.UnavailableCategory.NO_MUTATION_CONFIRMED); - } + // 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( + "evaluate", + session -> + new RateLimitOutcome.Evaluated( + decisionOf( + policy, + session.await( + scripts.evaluate( + session.commands(), + keys.counterKey(policy, request.subjectDigest()), + policy, + request.cost())), + now)), + () -> unavailable(policy, RateLimitOutcome.UnavailableCategory.UNAVAILABLE_BEFORE_SEND), + () -> unavailable(policy, RateLimitOutcome.UnavailableCategory.NO_MUTATION_CONFIRMED)); } private RateLimitOutcome unavailable( diff --git a/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories index b17e600c..f249dd9f 100644 --- a/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories +++ b/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories @@ -1,2 +1,6 @@ org.springframework.boot.EnvironmentPostProcessor=\ dev.caskeleton.adapter.outbound.cache.redis.capability.RedisReadinessGroupPostProcessor + +# Which roles need Redis for correctness. The runtime asks; this module owns the selectors. +dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCorrectnessRequirement=\ +dev.caskeleton.adapter.outbound.cache.redis.capability.RedisCorrectnessRoleSelectors diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java index 32f97ab2..22b34e09 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisRuntime.java @@ -1,17 +1,17 @@ package dev.caskeleton.adapter.outbound.cache.redis; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCredentialResolver.RedisCredentials; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisCredentialRole; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisTopologyClientFactory; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCredentialResolver.RedisCredentials; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisTopologyClientFactory; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; -import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -34,7 +34,7 @@ public final class LiveRedisRuntime { */ public static RedisRuntimeOwner open(RedisNamespace namespace, boolean separateScriptAccount) { RedisTopologyEndpoint endpoint = RedisTopologyEndpoint.fromSystemProperties(); - RedisSdkSettings settings = new RedisSdkSettings(); + RedisRuntimeSettings settings = new RedisRuntimeSettings(); settings.setEnabled(true); settings.setMode(endpoint.mode()); settings.setNodes(new ArrayList<>(List.of(endpoint.host() + ":" + endpoint.port()))); @@ -42,18 +42,18 @@ public final class LiveRedisRuntime { settings.getNamespace().setService(namespace.service()); settings.getNamespace().setDomain(namespace.domain()); - Map accounts = new EnumMap<>(RedisCredentialRole.class); + Map accounts = new java.util.LinkedHashMap<>(); accounts.put( - RedisCredentialRole.APPLICATION, + RedisAccount.APPLICATION, new RedisCredentials( endpoint.username(), endpoint.password().isBlank() ? "fixture-application" : endpoint.password())); if (separateScriptAccount) { accounts.put( - RedisCredentialRole.ADVANCED, + RedisAccount.ADVANCED, new RedisCredentials("ca-skeleton-application-advanced", "fixture-advanced")); } - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new java.util.LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java index bf12d04e..dc898f50 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java @@ -7,15 +7,18 @@ import dev.caskeleton.adapter.outbound.cache.redis.idempotency.IdempotencyScript import dev.caskeleton.adapter.outbound.cache.redis.idempotency.RedisIdempotencyStoreAdapter; import dev.caskeleton.adapter.outbound.cache.redis.lease.LeaseScripts; import dev.caskeleton.adapter.outbound.cache.redis.lease.RedisDistributedLeaseAdapter; +import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitAlgorithm; +import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitFailurePolicy; import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitKeys; +import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitPolicy; import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitScripts; import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RedisEdgeRateLimitAdapter; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.application.cache.CacheLookup; import dev.caskeleton.application.cache.CacheRecordIntent; import dev.caskeleton.application.cache.CacheRecordMetadata; @@ -30,10 +33,7 @@ import dev.caskeleton.application.lease.LeaseAcquireOutcome; import dev.caskeleton.application.lease.LeaseAttempt; import dev.caskeleton.application.lease.LeaseRequest; import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.shared.ratelimit.RateLimitAlgorithm; -import dev.caskeleton.shared.ratelimit.RateLimitFailurePolicy; import dev.caskeleton.shared.ratelimit.RateLimitOutcome; -import dev.caskeleton.shared.ratelimit.RateLimitPolicy; import dev.caskeleton.shared.ratelimit.RateLimitRequest; import dev.caskeleton.shared.ratelimit.RateParameters; import java.nio.charset.StandardCharsets; @@ -254,7 +254,7 @@ class LiveRedisSemanticPortsTest { private static long fieldCount(RedisRuntimeOwner runtime, byte[] key) throws Exception { try (RedisLease lease = runtime.borrow(RedisConnectionKind.REGULAR)) { - return lease.gateway().hashSize(key).toCompletableFuture().get(2, TimeUnit.SECONDS); + return lease.driver().commands().hlen(key).toCompletableFuture().get(2, TimeUnit.SECONDS); } } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScriptTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScriptTest.java new file mode 100644 index 00000000..8231c0da --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RegisteredLuaScriptTest.java @@ -0,0 +1,118 @@ +package dev.caskeleton.adapter.outbound.cache.redis; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class RegisteredLuaScriptTest { + + private static final byte[] KEY = "prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8); + + @Test + void aProgramIsLoadedOnceAndThenRunByDigest() { + // given + ScriptedServer server = new ScriptedServer(); + RegisteredLuaScript program = new RegisteredLuaScript("return 1"); + + // when + program.evaluateForLong(server.commands(), KEY, List.of()).toCompletableFuture().join(); + program.evaluateForLong(server.commands(), KEY, List.of()).toCompletableFuture().join(); + + // then + assertThat(server.calls).containsExactly("load", "eval:digest-1", "eval:digest-1"); + } + + @Test + @DisplayName("NOSCRIPT 타입 응답이면 다시 올린 뒤 정확히 한 번만 재실행한다") + void aForgottenProgramIsReloadedAndRetriedExactlyOnce() { + // given + ScriptedServer server = new ScriptedServer(); + server.failNext(new io.lettuce.core.RedisNoScriptException("NOSCRIPT No matching script")); + RegisteredLuaScript program = new RegisteredLuaScript("return 1"); + + // when + program.evaluateForLong(server.commands(), KEY, List.of()).toCompletableFuture().join(); + + // then + assertThat(server.calls).containsExactly("load", "eval:digest-1", "load", "eval:digest-2"); + } + + @Test + void aFailureThatIsNotNoScriptIsNeitherReloadedNorRetried() { + // given + ScriptedServer server = new ScriptedServer(); + server.failNext(new io.lettuce.core.RedisCommandExecutionException("NOPERM denied")); + RegisteredLuaScript program = new RegisteredLuaScript("return 1"); + + // when + Throwable failure = + catchThrowable( + () -> + program + .evaluateForLong(server.commands(), KEY, List.of()) + .toCompletableFuture() + .join()); + + // then + assertThat(failure) + .hasRootCauseInstanceOf(io.lettuce.core.RedisCommandExecutionException.class) + .hasRootCauseMessage("NOPERM denied"); + } + + @Test + void aShortReplyIsRefusedWithTheProgramsName() { + // when + Throwable failure = + catchThrowable(() -> RegisteredLuaScript.requireShape(List.of(1L), 3, "lease")); + + // then + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("the lease program answered with 1 values; 3 were expected"); + } + + /** Counts loads and evaluations, and fails an evaluation on request. */ + private static final class ScriptedServer { + + private final List calls = new ArrayList<>(); + private final Deque failures = new ArrayDeque<>(); + private int loads; + + void failNext(RuntimeException failure) { + failures.add(failure); + } + + SemanticRedisCommands commands() { + return (SemanticRedisCommands) + Proxy.newProxyInstance( + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, + (proxy, method, arguments) -> + switch (method.getName()) { + case "loadScript" -> { + calls.add("load"); + loads++; + yield CompletableFuture.completedFuture("digest-" + loads); + } + case "evaluateRegisteredForLong" -> { + calls.add("eval:" + arguments[0]); + RuntimeException failure = failures.poll(); + yield failure == null + ? CompletableFuture.completedFuture(1L) + : CompletableFuture.failedFuture(failure); + } + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + } +} 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 46337e42..015d5b65 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 @@ -2,13 +2,15 @@ package dev.caskeleton.adapter.outbound.cache.redis.cache; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.InMemoryGatewayAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +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.RedisRuntimeClient; +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.AuthoritativeAbsence; import dev.caskeleton.application.cache.CacheInvalidationOutcome; import dev.caskeleton.application.cache.CacheLookup; @@ -21,7 +23,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.EnumMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.DisplayName; @@ -39,14 +40,14 @@ class RedisCacheRegionAdapterTest { private static final Instant T0 = Instant.parse("2026-08-10T12:00:00Z"); - private final InMemoryGatewayAccess gateway = InMemoryGatewayAccess.create(); + private final InMemorySemanticRedisCommands gateway = new InMemorySemanticRedisCommands(); private final RedisCacheRegionAdapter.CacheKeys keys = new RedisCacheRegionAdapter.CacheKeys( new RedisNamespace("prod", "ca-skeleton", "shared"), "orders", 1); private RedisCacheRegionAdapter cache(Instant now) { - return cache(now, new StubClient(gateway.gateway())); + return cache(now, StubRedisRuntimeClient.serving(gateway)); } private RedisCacheRegionAdapter cache(Instant now, RedisRuntimeClient client) { @@ -55,7 +56,7 @@ class RedisCacheRegionAdapterTest { private RedisCacheRegionAdapter cache( Instant now, RedisRuntimeClient client, RedisCacheRegionAdapter.CacheKeys cacheKeys) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new java.util.LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } @@ -224,9 +225,9 @@ class RedisCacheRegionAdapterTest { new RedisNamespace("prod", "ca-skeleton", "shared"), "orders-shared", 1); RedisCacheRegionAdapter first = - cache(T0, new StubClient(gateway.gateway()), firstKeys); + cache(T0, StubRedisRuntimeClient.serving(gateway), firstKeys); RedisCacheRegionAdapter second = - cache(T0, new StubClient(gateway.gateway()), secondKeys); + cache(T0, StubRedisRuntimeClient.serving(gateway), secondKeys); second.record("order-1", "payload", upsert()); assertThat(second.lookup("order-1")).isInstanceOf(CacheLookup.Hit.class); @@ -240,7 +241,7 @@ class RedisCacheRegionAdapterTest { // The same process state (secondKeys) is reused with a later clock. Once the positive soft TTL // elapses it must sample the server generation again and stop serving the old region entry. RedisCacheRegionAdapter secondAfterRecheck = - cache(T0.plusSeconds(31), new StubClient(gateway.gateway()), secondKeys); + cache(T0.plusSeconds(31), StubRedisRuntimeClient.serving(gateway), secondKeys); CacheLookup lookup = secondAfterRecheck.lookup("order-1"); assertThat(lookup).isInstanceOf(CacheLookup.Miss.class); @@ -329,7 +330,8 @@ class RedisCacheRegionAdapterTest { @DisplayName("보낸 뒤 응답을 잃은 SET은 적용됐을 수 있으므로 INDETERMINATE다") void aWriteWhoseReplyWasLostIsIndeterminate() { // given - RedisCacheRegionAdapter cache = cache(T0, new StubClient(losingReplyOf("set"))); + RedisCacheRegionAdapter cache = + cache(T0, StubRedisRuntimeClient.serving(losingReplyOf("set"))); // when CacheRecordOutcome outcome = cache.record("order-1", "payload", upsert()); @@ -343,7 +345,7 @@ class RedisCacheRegionAdapterTest { void aWriteThatFailedBeforeItsSetWasSentDegrades() { // given RedisCacheRegionAdapter cache = - cache(T0, new StubClient(losingReplyOf("incrementBy"))); + cache(T0, StubRedisRuntimeClient.serving(losingReplyOf("incrementBy"))); // when CacheRecordOutcome outcome = cache.record("order-1", "payload", upsert()); @@ -357,7 +359,7 @@ class RedisCacheRegionAdapterTest { void anInvalidationWhoseReplyWasLostIsIndeterminate() { // given RedisCacheRegionAdapter cache = - cache(T0, new StubClient(losingReplyOf("getAndDelete"))); + cache(T0, StubRedisRuntimeClient.serving(losingReplyOf("getAndDelete"))); // when CacheInvalidationOutcome outcome = cache.invalidate("order-1"); @@ -371,7 +373,7 @@ class RedisCacheRegionAdapterTest { void aRegionInvalidationWhoseReplyWasLostIsIndeterminate() { // given RedisCacheRegionAdapter cache = - cache(T0, new StubClient(losingReplyOf("incrementBy"))); + cache(T0, StubRedisRuntimeClient.serving(losingReplyOf("incrementBy"))); // when CacheInvalidationOutcome outcome = cache.invalidateRegion(); @@ -381,12 +383,12 @@ class RedisCacheRegionAdapterTest { } /** The in-memory gateway, except that one command's reply is lost after it was sent. */ - private RedisCommandGateway losingReplyOf(String command) { - RedisCommandGateway real = gateway.gateway(); - return (RedisCommandGateway) + private SemanticRedisCommands losingReplyOf(String command) { + SemanticRedisCommands real = gateway; + return (SemanticRedisCommands) Proxy.newProxyInstance( - RedisCommandGateway.class.getClassLoader(), - new Class[] {RedisCommandGateway.class}, + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, (proxy, method, arguments) -> method.getName().equals(command) ? CompletableFuture.failedFuture(new RuntimeException("reply lost")) @@ -410,14 +412,11 @@ class RedisCacheRegionAdapterTest { private void writeRaw(String key, byte[] stored) { try { gateway - .gateway() .set( keys.entryKey("digest-" + key), stored, - dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.WritePresence - .ALWAYS, - new dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Expiration.After( - Duration.ofMinutes(10))) + dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence.ALWAYS, + Duration.ofMinutes(10)) .toCompletableFuture() .join(); } catch (RuntimeException failure) { @@ -425,36 +424,6 @@ class RedisCacheRegionAdapterTest { } } - private record StubClient(RedisCommandGateway gateway) implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return gateway; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } - private static final class BrokenClient implements RedisRuntimeClient { @Override @@ -463,8 +432,7 @@ class RedisCacheRegionAdapterTest { } @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { + public RedisLaneConnection openLane(RedisLane kind, java.util.Optional routingKey) { throw new IllegalStateException("the server is unreachable"); } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/LiveRedisSemanticScriptAclProbeTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/LiveRedisSemanticScriptAclProbeTest.java index a983450e..33ab9c5d 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/LiveRedisSemanticScriptAclProbeTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/LiveRedisSemanticScriptAclProbeTest.java @@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.cache.redis.LiveRedisRuntime; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; import java.nio.charset.StandardCharsets; import java.time.Duration; diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java index 8228719f..88560f25 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.application.outbound.SecretSourcePort; import java.time.Clock; import java.util.ArrayList; diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java index 9e14be4b..2f424036 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java @@ -3,8 +3,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import dev.caskeleton.application.cache.CacheRegionPort; import dev.caskeleton.application.idempotency.IdempotencyStorePort; @@ -40,7 +40,7 @@ class RedisCapabilityCompositionTest { private final ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)) .withBean( "compositionOnlyRedisSemanticScriptAclProbe", RedisSemanticScriptAclProbe.class, @@ -100,7 +100,7 @@ class RedisCapabilityCompositionTest { // Every call would answer "unknown policy", which the port reports as a deployment error per // request rather than once, at the only moment anybody is looking. new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)) .withUserConfiguration(RedisCapabilityConfig.class, Support.class) .withPropertyValues( "app.redis.enabled=true", @@ -170,7 +170,7 @@ class RedisCapabilityCompositionTest { void theSwitchOffLeavesNoRedisBeanWhateverTheRolesSay() { new ApplicationContextRunner() .withConfiguration( - AutoConfigurations.of(RedisSdkAutoConfiguration.class, RedisCapabilityConfig.class)) + AutoConfigurations.of(RedisRuntimeAutoConfiguration.class, RedisCapabilityConfig.class)) .withUserConfiguration(Support.class) .withPropertyValues( "app.redis.enabled=false", diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecretsTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecretsTest.java new file mode 100644 index 00000000..4429b5a1 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisProductionSecretsTest.java @@ -0,0 +1,80 @@ +package dev.caskeleton.adapter.outbound.cache.redis.capability; + +import static org.assertj.core.api.Assertions.assertThat; + +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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.mock.env.MockEnvironment; + +/** + * Which production secrets each selected Redis role needs — the rule the composition root's secret + * guard used to spell out itself, one Redis role prefix at a time. + */ +class RedisProductionSecretsTest { + + private final RedisProductionSecrets secrets = new RedisProductionSecrets(); + + static Stream selectedRoles() { + return Stream.of( + Arguments.of( + "ca-skeleton.capabilities.cache.bindings.default", + "redis", + List.of("APP_CACHE_REDIS_PASSWORD", "APP_CACHE_REDIS_KEY_HMAC_SECRET")), + Arguments.of( + "ca-skeleton.security.auth-mode", + "redis-session", + List.of("APP_SESSION_REDIS_PASSWORD", "APP_SESSION_REDIS_KEY_HMAC_SECRET")), + Arguments.of( + "ca-skeleton.capabilities.idempotency.provider", + "redis", + List.of("APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET")), + Arguments.of( + "ca-skeleton.capabilities.rate-limit.provider", + "redis", + List.of("APP_RATE_LIMIT_REDIS_PASSWORD", "APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET")), + Arguments.of( + "ca-skeleton.capabilities.lease.provider", + "redis", + List.of("APP_LEASE_REDIS_KEY_HMAC_SECRET"))); + } + + @ParameterizedTest(name = "{0}={1}") + @MethodSource("selectedRoles") + @DisplayName("선택된 Redis 역할은 자기 production secret만 요구한다") + void aSelectedRoleRequiresExactlyItsOwnSecrets( + String selector, String value, List expected) { + // given + MockEnvironment environment = new MockEnvironment().withProperty(selector, value); + + // when + List required = secrets.requiredSecrets(environment); + + // then + assertThat(required).containsExactlyElementsOf(expected); + } + + @Test + @DisplayName("Redis가 켜져 있어도 역할이 선택되지 않았으면 역할 secret을 요구하지 않는다") + void noSelectedRoleRequiresNoRoleSecret() { + assertThat(secrets.requiredSecrets(new MockEnvironment())).isEmpty(); + } + + @Test + void aRoleSelectingAnotherProviderRequiresNothingOfRedis() { + // given + MockEnvironment environment = + new MockEnvironment() + .withProperty("ca-skeleton.capabilities.rate-limit.provider", "disabled"); + + // when + List required = secrets.requiredSecrets(environment); + + // then + assertThat(required).isEmpty(); + } +} 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 8557e188..d33bbea3 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 @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.capability; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCorrectnessRoles; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCorrectnessRoles; import dev.caskeleton.adapter.outbound.support.startup.ReadinessGroup; import java.io.IOException; import java.util.ArrayList; @@ -148,7 +148,10 @@ class RedisReadinessGroupPostProcessorTest { @Test @DisplayName("every correctness selector makes the post-processor append Redis readiness") void eachCorrectnessSelectorAppendsRedisReadiness() throws IOException { - for (Map.Entry selector : RedisCorrectnessRoles.selectors().entrySet()) { + for (RedisCorrectnessRoleSelectors.Role role : + RedisCorrectnessRoleSelectors.ROLES.stream() + .filter(RedisCorrectnessRoleSelectors.Role::correctness) + .toList()) { StandardEnvironment environment = new StandardEnvironment(); environment .getPropertySources() @@ -160,14 +163,14 @@ class RedisReadinessGroupPostProcessorTest { shippedReadinessInclude(), "app.redis.enabled", "true", - selector.getKey(), - selector.getValue()))); + role.selector(), + role.selecting()))); new RedisReadinessGroupPostProcessor() .postProcessEnvironment(environment, new SpringApplication()); assertThat(environment.getProperty(ReadinessGroup.INCLUDE_PROPERTY)) - .as("%s=%s", selector.getKey(), selector.getValue()) + .as("%s=%s", role.selector(), role.selecting()) .contains("readinessState", RedisCorrectnessRoles.REQUIRED_HEALTH_CONTRIBUTOR); } } @@ -180,7 +183,7 @@ class RedisReadinessGroupPostProcessorTest { HealthContributorAutoConfiguration.class, AvailabilityHealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration.class + dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration.class }) static class HealthContext { @@ -190,7 +193,7 @@ class RedisReadinessGroupPostProcessorTest { } @Bean - dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration + dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration .RedisSecretSource stubSecretSource() { // Supplies the credential the enabled cases require, without putting one in the process 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 aaf5826d..4b237800 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 @@ -5,17 +5,18 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; import java.lang.reflect.Proxy; import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.EnumMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; @@ -104,7 +105,7 @@ class RedisSemanticScriptAclProbeTest { .hasMessageContaining("SCRIPT LOAD/EVALSHA is unavailable"); } - private static RedisRuntimeOwner owner(RedisCommandGateway gateway, AtomicInteger opened) { + private static RedisRuntimeOwner owner(SemanticRedisCommands gateway, AtomicInteger opened) { RedisRuntimeClient client = new RedisRuntimeClient() { @Override @@ -113,15 +114,21 @@ class RedisSemanticScriptAclProbeTest { } @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, Optional routingKey) { + public RedisLaneConnection openLane(RedisLane kind, Optional routingKey) { opened.incrementAndGet(); return new RedisLaneConnection() { @Override - public RedisCommandGateway gateway() { + public SemanticRedisCommands commands() { return gateway; } + @Override + public dev.caskeleton.adapter.outbound.cache.redis.runtime.connection + .RedisDriverConnection + driver() { + throw new UnsupportedOperationException(); + } + @Override public boolean open() { return true; @@ -135,18 +142,18 @@ class RedisSemanticScriptAclProbeTest { @Override public void close() {} }; - EnumMap limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new java.util.LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 1); } return new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)); } - private static RedisCommandGateway gateway(boolean denyScripts) { - return (RedisCommandGateway) + private static SemanticRedisCommands gateway(boolean denyScripts) { + return (SemanticRedisCommands) Proxy.newProxyInstance( - RedisCommandGateway.class.getClassLoader(), - new Class[] {RedisCommandGateway.class}, + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, (proxy, method, arguments) -> switch (method.getName()) { case "loadScript" -> @@ -169,12 +176,12 @@ class RedisSemanticScriptAclProbeTest { *

Redis checks a script's inner commands against the caller's ACL when they run, so a program * that calls the denied command fails with {@code NOPERM} and one that does not call it succeeds. */ - private static RedisCommandGateway gatewayDenying(String command) { + private static SemanticRedisCommands gatewayDenying(String command) { AtomicReference loaded = new AtomicReference<>(""); - return (RedisCommandGateway) + return (SemanticRedisCommands) Proxy.newProxyInstance( - RedisCommandGateway.class.getClassLoader(), - new Class[] {RedisCommandGateway.class}, + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, (proxy, method, arguments) -> switch (method.getName()) { case "loadScript" -> { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScriptsConcurrencyContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScriptsConcurrencyContractTest.java deleted file mode 100644 index de03121f..00000000 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScriptsConcurrencyContractTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.lang.reflect.Field; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -/** Pins the script-digest cache so request threads never mutate a shared map structure. */ -class IdempotencyScriptsConcurrencyContractTest { - - @Test - void digestSlotsArePreallocatedAndStructurallyImmutable() throws Exception { - IdempotencyScripts scripts = new IdempotencyScripts(); - Field field = IdempotencyScripts.class.getDeclaredField("digests"); - field.setAccessible(true); - - @SuppressWarnings("unchecked") - Map> digests = - (Map>) field.get(scripts); - - assertThat(digests).containsOnlyKeys("claim", "transition", "release", "inspect"); - assertThat(digests.values()).allSatisfy(slot -> assertThat(slot.get()).isNull()); - assertThatThrownBy(() -> digests.put("runtime-added", new AtomicReference<>())) - .isInstanceOf(UnsupportedOperationException.class); - } -} 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 1dcf75b4..db1ca3d3 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 @@ -2,13 +2,14 @@ package dev.caskeleton.adapter.outbound.cache.redis.idempotency; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.InMemoryGatewayAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +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.RedisRuntimeClient; +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.IdempotencyClaimAttempt; import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; @@ -29,7 +30,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.EnumMap; import java.util.Map; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; @@ -62,9 +62,10 @@ class RedisIdempotencyStoreAdapterTest { private static final OperationId OTHER_OPERATION = new OperationId("operation-bbbbbbbbbb"); - private final InMemoryGatewayAccess gateway = InMemoryGatewayAccess.create(); + private final InMemorySemanticRedisCommands gateway = new InMemorySemanticRedisCommands(); - private final RedisIdempotencyStoreAdapter store = store(T0, new StubClient(gateway.gateway())); + private final RedisIdempotencyStoreAdapter store = + store(T0, StubRedisRuntimeClient.serving(gateway)); private RedisIdempotencyStoreAdapter store(Instant now, RedisRuntimeClient client) { return store(now, owner(client, 4, Duration.ofSeconds(1))); @@ -72,7 +73,7 @@ class RedisIdempotencyStoreAdapterTest { private static RedisRuntimeOwner owner( RedisRuntimeClient client, int connectionsPerLane, Duration acquireTimeout) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new java.util.LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, connectionsPerLane); } @@ -83,7 +84,7 @@ class RedisIdempotencyStoreAdapterTest { * An owner with one script connection and almost no patience, so holding it saturates the lane. */ private RedisRuntimeOwner narrowOwner() { - return owner(new StubClient(gateway.gateway()), 1, Duration.ofMillis(10)); + return owner(StubRedisRuntimeClient.serving(gateway), 1, Duration.ofMillis(10)); } private RedisIdempotencyStoreAdapter store(Instant now, RedisRuntimeOwner owner) { @@ -264,7 +265,7 @@ class RedisIdempotencyStoreAdapterTest { // The first holder went away. Advancing the Redis fixture clock, not the caller JVM clock, // expires the distributed processing lease. gateway.advance(Duration.ofSeconds(60)); - RedisIdempotencyStoreAdapter later = store(T0, new StubClient(gateway.gateway())); + RedisIdempotencyStoreAdapter later = store(T0, StubRedisRuntimeClient.serving(gateway)); IdempotencyClaimOutcome outcome = later.claim( new IdempotencyClaimRequest( @@ -394,36 +395,6 @@ class RedisIdempotencyStoreAdapterTest { return store.markExecutionStarted(owner, OPERATION).owner().orElseThrow(); } - private record StubClient(RedisCommandGateway gateway) implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return gateway; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } - private static final class BrokenClient implements RedisRuntimeClient { @Override @@ -432,8 +403,7 @@ class RedisIdempotencyStoreAdapterTest { } @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { + public RedisLaneConnection openLane(RedisLane kind, java.util.Optional routingKey) { throw new IllegalStateException("the server is unreachable"); } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScriptsTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScriptsTest.java new file mode 100644 index 00000000..594cc31e --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LeaseScriptsTest.java @@ -0,0 +1,53 @@ +package dev.caskeleton.adapter.outbound.cache.redis.lease; + +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 java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class LeaseScriptsTest { + + private static final byte[] KEY = "prod:svc:shared:lease:v1:p:r".getBytes(StandardCharsets.UTF_8); + + @Test + @DisplayName("NOSCRIPT가 예외 타입이 아니라 메시지로만 와도 lease 프로그램을 다시 올리고 한 번 재실행한다") + void aProgramTheServerForgotIsReloadedEvenWhenOnlyTheMessageSaysNoScript() { + // given + SemanticRedisCommands server = forgettingOnce(new InMemorySemanticRedisCommands()); + LeaseScripts scripts = new LeaseScripts(); + + // when + LeaseScripts.Reply reply = + scripts.acquire(server, KEY, "owner:operation", 30_000).toCompletableFuture().join(); + + // then + assertThat(reply.status()).isEqualTo(1L); + } + + /** + * A server that has lost every loaded script once, and says so the way a proxy or a wrapped + * driver error does: a generic command failure whose message starts with {@code NOSCRIPT}. + */ + private static SemanticRedisCommands forgettingOnce(SemanticRedisCommands delegate) { + AtomicBoolean forgotten = new AtomicBoolean(); + return (SemanticRedisCommands) + Proxy.newProxyInstance( + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, + (proxy, method, arguments) -> { + if (method.getName().startsWith("evaluateRegistered") + && forgotten.compareAndSet(false, true)) { + return CompletableFuture.failedFuture( + new io.lettuce.core.RedisCommandExecutionException( + "NOSCRIPT No matching script. Please use EVAL.")); + } + return method.invoke(delegate, arguments); + }); + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LiveRedisDistributedLeaseContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LiveRedisDistributedLeaseContractTest.java new file mode 100644 index 00000000..f8199492 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/LiveRedisDistributedLeaseContractTest.java @@ -0,0 +1,65 @@ +package dev.caskeleton.adapter.outbound.cache.redis.lease; + +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.lease.DistributedLeasePort; +import dev.caskeleton.application.lease.testkit.DistributedLeaseContract; +import java.time.Clock; +import java.time.Duration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; + +/** + * The Redis adapter, against a real server under the deployment's advanced account, held to the + * same ownership contract as the fake. + * + *

The owner check is Lua on the server; only a real server proves the programs compare what the + * fake's emulation says they compare. Time passes for real here, so the lease is short. + */ +@Tag("redis-topology") +@Tag("lane-standalone") +@Tag("lane-cluster") +class LiveRedisDistributedLeaseContractTest extends DistributedLeaseContract { + + 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 DistributedLeasePort newPort() { + owner = LiveRedisRuntime.open(NAMESPACE, true); + return new RedisDistributedLeaseAdapter( + owner, + new RedisDistributedLeaseAdapter.LeaseKeys(NAMESPACE, 1), + new LeaseScripts(), + Clock.systemUTC(), + System::nanoTime, + Duration.ofSeconds(2), + Duration.ofMillis(50), + Duration.ZERO); + } + + @Override + protected Duration leaseTtl() { + return Duration.ofMillis(400); + } + + @Override + protected void elapse(Duration duration) { + try { + Thread.sleep(duration.toMillis()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while letting the lease expire", interrupted); + } + } +} 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 48c7786e..249554b2 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 @@ -3,13 +3,14 @@ package dev.caskeleton.adapter.outbound.cache.redis.lease; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.InMemoryGatewayAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +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.RedisRuntimeClient; +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.lease.LeaseAcquireOutcome; import dev.caskeleton.application.lease.LeaseAttempt; import dev.caskeleton.application.lease.LeaseHandle; @@ -24,7 +25,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @@ -56,11 +56,12 @@ class RedisDistributedLeaseAdapterTest { private static final String OPERATION_B = "operation-bbbbbbbbbb"; - private final InMemoryGatewayAccess gateway = InMemoryGatewayAccess.create(); + private final InMemorySemanticRedisCommands gateway = new InMemorySemanticRedisCommands(); private final AtomicLong nanos = new AtomicLong(); - private final RedisDistributedLeaseAdapter adapter = adapter(new StubClient(gateway.gateway())); + private final RedisDistributedLeaseAdapter adapter = + adapter(StubRedisRuntimeClient.serving(gateway)); private RedisDistributedLeaseAdapter adapter(RedisRuntimeClient client) { return adapter(client, Duration.ZERO); @@ -72,7 +73,7 @@ class RedisDistributedLeaseAdapterTest { private static RedisRuntimeOwner owner( RedisRuntimeClient client, int connectionsPerLane, Duration acquireTimeout) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new java.util.LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, connectionsPerLane); } @@ -83,7 +84,7 @@ class RedisDistributedLeaseAdapterTest { * An owner with one script connection and almost no patience, so holding it saturates the lane. */ private RedisRuntimeOwner narrowOwner() { - return owner(new StubClient(gateway.gateway()), 1, Duration.ofMillis(10)); + return owner(StubRedisRuntimeClient.serving(gateway), 1, Duration.ofMillis(10)); } private RedisDistributedLeaseAdapter adapter(RedisRuntimeOwner owner, Duration driftBudget) { @@ -179,7 +180,7 @@ class RedisDistributedLeaseAdapterTest { assertThat(acquired).isInstanceOf(LeaseAcquireOutcome.Acquired.class); RedisDistributedLeaseAdapter recovering = - adapter(new StubClient(gateway.gateway()), Duration.ofSeconds(2)); + adapter(StubRedisRuntimeClient.serving(gateway), Duration.ofSeconds(2)); LeaseInspectionOutcome inspection = recovering.inspect(new LeaseInspectionRequest(PURPOSE, RESOURCE, attempt)); @@ -374,7 +375,7 @@ class RedisDistributedLeaseAdapterTest { void aTtlWithinTheDriftBudgetIsRejectedBeforeReachingRedis() { // given RedisDistributedLeaseAdapter drifted = - adapter(new StubClient(gateway.gateway()), Duration.ofSeconds(2)); + adapter(StubRedisRuntimeClient.serving(gateway), Duration.ofSeconds(2)); LeaseAttempt attempt = drifted.newAttempt(OPERATION_A); // when @@ -392,7 +393,7 @@ class RedisDistributedLeaseAdapterTest { void aTtlWithinTheDriftBudgetLeavesTheResourceFree() { // given RedisDistributedLeaseAdapter drifted = - adapter(new StubClient(gateway.gateway()), Duration.ofSeconds(2)); + adapter(StubRedisRuntimeClient.serving(gateway), Duration.ofSeconds(2)); LeaseAttempt attempt = drifted.newAttempt(OPERATION_A); // when @@ -409,7 +410,7 @@ class RedisDistributedLeaseAdapterTest { void aRenewTtlWithinTheDriftBudgetIsRejectedBeforeReachingRedis() { // given RedisDistributedLeaseAdapter drifted = - adapter(new StubClient(gateway.gateway()), Duration.ofSeconds(2)); + adapter(StubRedisRuntimeClient.serving(gateway), Duration.ofSeconds(2)); LeaseHandle handle = ((LeaseAcquireOutcome.Acquired) drifted.tryAcquire( @@ -436,36 +437,6 @@ class RedisDistributedLeaseAdapterTest { assertThat(first.ownerToken()).hasSizeGreaterThanOrEqualTo(16); } - private record StubClient(RedisCommandGateway gateway) implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return gateway; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } - private static final class BrokenClient implements RedisRuntimeClient { @Override @@ -474,8 +445,7 @@ class RedisDistributedLeaseAdapterTest { } @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { + public RedisLaneConnection openLane(RedisLane kind, java.util.Optional routingKey) { throw new IllegalStateException("the server is unreachable"); } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseContractTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseContractTest.java new file mode 100644 index 00000000..d39840a3 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseContractTest.java @@ -0,0 +1,45 @@ +package dev.caskeleton.adapter.outbound.cache.redis.lease; + +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.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.lease.DistributedLeasePort; +import dev.caskeleton.application.lease.testkit.DistributedLeaseContract; +import java.time.Clock; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +/** The Redis adapter, over the runtime's in-memory commands, held to the port's contract. */ +class RedisDistributedLeaseContractTest extends DistributedLeaseContract { + + private final InMemorySemanticRedisCommands server = new InMemorySemanticRedisCommands(); + + private final AtomicLong nanos = new AtomicLong(); + + @Override + protected DistributedLeasePort newPort() { + return new RedisDistributedLeaseAdapter( + new RedisRuntimeOwner( + StubRedisRuntimeClient.serving(server), + Map.of(RedisConnectionKind.REGULAR, 4, RedisConnectionKind.SCRIPT, 4), + Duration.ofSeconds(1), + Duration.ofSeconds(1)), + new RedisDistributedLeaseAdapter.LeaseKeys( + new RedisNamespace("prod", "ca-skeleton", "shared"), 1), + new LeaseScripts(), + Clock.systemUTC(), + nanos::get, + Duration.ofSeconds(2), + Duration.ofMillis(50), + Duration.ZERO); + } + + @Override + protected void elapse(Duration duration) { + server.advance(duration); + nanos.addAndGet(duration.toNanos()); + } +} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitEvaluationDedupPolicyTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicyTest.java similarity index 96% rename from src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitEvaluationDedupPolicyTest.java rename to src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicyTest.java index fa095a9a..2000f5d8 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitEvaluationDedupPolicyTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitEvaluationDedupPolicyTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.shared.ratelimit; +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitPolicyTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java similarity index 98% rename from src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitPolicyTest.java rename to src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java index ac12acab..760976eb 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/RateLimitPolicyTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RateLimitPolicyTest.java @@ -1,8 +1,9 @@ -package dev.caskeleton.shared.ratelimit; +package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.shared.ratelimit.RateParameters; import java.time.Duration; import org.junit.jupiter.api.Test; 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 b81d9791..f6529eb9 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 @@ -2,26 +2,22 @@ package dev.caskeleton.adapter.outbound.cache.redis.ratelimit; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.InMemoryGatewayAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; -import dev.caskeleton.shared.ratelimit.RateLimitAlgorithm; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +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.RedisRuntimeClient; +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.shared.ratelimit.RateLimitDecision; -import dev.caskeleton.shared.ratelimit.RateLimitEvaluationDedupPolicy; -import dev.caskeleton.shared.ratelimit.RateLimitFailurePolicy; import dev.caskeleton.shared.ratelimit.RateLimitOutcome; -import dev.caskeleton.shared.ratelimit.RateLimitPolicy; import dev.caskeleton.shared.ratelimit.RateLimitRequest; import dev.caskeleton.shared.ratelimit.RateParameters; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.EnumMap; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -47,18 +43,18 @@ class RedisEdgeRateLimitAdapterTest { private static final String EVALUATION_ID = "ev1:AAAAAAAAAAAAAAAAAAAAAA"; - private final InMemoryGatewayAccess gateway = InMemoryGatewayAccess.create(); + private final InMemorySemanticRedisCommands gateway = new InMemorySemanticRedisCommands(); private final RateLimitKeys keys = new RateLimitKeys(new RedisNamespace("prod", "ca-skeleton", "shared"), 1); private RedisEdgeRateLimitAdapter adapter(RateLimitPolicy policy, Clock clock) { - return adapter(policy, clock, new StubClient(gateway.gateway())); + return adapter(policy, clock, StubRedisRuntimeClient.serving(gateway)); } private RedisEdgeRateLimitAdapter adapter( RateLimitPolicy policy, Clock clock, RedisRuntimeClient client) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new java.util.LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } @@ -269,35 +265,6 @@ class RedisEdgeRateLimitAdapterTest { } /** Hands out the shared in-memory gateway; the owner's pooling makes it one logical server. */ - private record StubClient(RedisCommandGateway gateway) implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return gateway; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } /** A server that cannot be reached at all. */ private static final class BrokenClient implements RedisRuntimeClient { @@ -308,8 +275,7 @@ class RedisEdgeRateLimitAdapterTest { } @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { + public RedisLaneConnection openLane(RedisLane kind, java.util.Optional routingKey) { throw new IllegalStateException("the server is unreachable"); } diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 8ebfb9ce..350fd1d3 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -580,8 +580,8 @@ holder 가 락을 잡을 수 있다. `spring.jpa.open-in-view`가 암묵 기본값일 때 WARN 만 찍을 뿐 명시적으로 `true`로 설정한 배포는 막지 못한다. WARN 은 놓치기 쉬우므로, resolved 값이 `true`면 운영자가 실제 설정한 `APP_DATASOURCE_OPEN_IN_VIEW` 키를 메시지에 담아 부팅을 실패시킨다. -- **읽기만 하고 re-bind 하지 않으며, 부재 값은 Spring 기본에 맡긴다.** `SmartInitializingSingleton` - 으로 한 번만 검사하고, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off +- **읽기만 하고 re-bind 하지 않으며, 부재 값은 Spring 기본에 맡긴다.** `StartupRule`로 위반만 + 돌려주고 support의 `StartupRuleRunner`가 모든 싱글톤 생성 후 한 번 실행하며, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off 가 기본)에 맡기며 *있는 `true`*만 거부한다. ### JpaDangerousConfigurationGuard (ddl-auto) diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java index 201dada4..07616961 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java @@ -2,55 +2,53 @@ package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; -import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; -import org.springframework.beans.factory.SmartInitializingSingleton; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import java.util.ArrayList; +import java.util.List; import org.springframework.core.env.Environment; /** * Keeps the Flyway prod safety nets on; raises PROFILE_MISMATCH (exit 71) when an override * re-enables a forbidden option. See README for the design rationale. */ -class FlywayProdSafetyValidator implements SmartInitializingSingleton { +class FlywayProdSafetyValidator implements StartupRule { static final String BASELINE_ON_MIGRATE_KEY = "spring.flyway.baseline-on-migrate"; static final String OUT_OF_ORDER_KEY = "spring.flyway.out-of-order"; static final String CLEAN_DISABLED_KEY = "spring.flyway.clean-disabled"; - private final Environment environment; - - public FlywayProdSafetyValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.PROFILE_CHECK; } @Override - public void afterSingletonsInstantiated() { + public String summary() { + return "prod profile forbids these Flyway options (feature-migration-startup-contract D2/D4)"; + } + + @Override + public String remedy() { + return "partial-schema recovery goes through runbook://migration/manual-recovery, never an" + + " in-prod Flyway repair."; + } + + @Override + public List violations(Environment environment) { if (!RuntimeProfileSnapshot.from(environment).isProduction()) { - return; + return List.of(); } - StartupValidationContext violations = - StartupValidationContext.forPhase(StartupPhase.PROFILE_CHECK); - if (isTrue(BASELINE_ON_MIGRATE_KEY)) { - violations.reject( - BASELINE_ON_MIGRATE_KEY + "=true (removes the missing-migration safety net)"); + List violations = new ArrayList<>(); + if (Boolean.parseBoolean(environment.getProperty(BASELINE_ON_MIGRATE_KEY))) { + violations.add(BASELINE_ON_MIGRATE_KEY + "=true (removes the missing-migration safety net)"); } - if (isTrue(OUT_OF_ORDER_KEY)) { - violations.reject(OUT_OF_ORDER_KEY + "=true (breaks migration ordering consistency)"); + if (Boolean.parseBoolean(environment.getProperty(OUT_OF_ORDER_KEY))) { + violations.add(OUT_OF_ORDER_KEY + "=true (breaks migration ordering consistency)"); } - if (isFalse(CLEAN_DISABLED_KEY)) { - violations.reject(CLEAN_DISABLED_KEY + "=false (re-arms destructive Flyway clean)"); + String cleanDisabled = environment.getProperty(CLEAN_DISABLED_KEY); + if (cleanDisabled != null && "false".equalsIgnoreCase(cleanDisabled.trim())) { + violations.add(CLEAN_DISABLED_KEY + "=false (re-arms destructive Flyway clean)"); } - violations.failIfViolated( - "prod profile forbids these Flyway options (feature-migration-startup-contract D2/D4)", - "partial-schema recovery goes through runbook://migration/manual-recovery, never an" - + " in-prod Flyway repair."); - } - - private boolean isTrue(String key) { - return Boolean.parseBoolean(environment.getProperty(key)); - } - - private boolean isFalse(String key) { - String value = environment.getProperty(key); - return value != null && "false".equalsIgnoreCase(value.trim()); + return violations; } } 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 6c793aee..309b73a4 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 @@ -1,19 +1,19 @@ package dev.caskeleton.adapter.outbound.persistence.startup; -import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import java.time.temporal.ChronoUnit; -import org.springframework.beans.factory.SmartInitializingSingleton; +import java.util.List; import org.springframework.boot.convert.DurationStyle; import org.springframework.core.env.Environment; /** * Fail-fast startup guard for HikariCP inter-knob constraints. Reads (never re-binds) resolved - * Spring properties as a {@link SmartInitializingSingleton}; an absent property is skipped. See - * README for the design rationale. + * Spring properties as a {@link StartupRule}; an absent property is skipped. See README for the + * design rationale. */ -class HikariPoolConstraintValidator implements SmartInitializingSingleton { +class HikariPoolConstraintValidator implements StartupRule { static final String CONNECTION_TIMEOUT_KEY = "spring.datasource.hikari.connection-timeout"; static final String VALIDATION_TIMEOUT_KEY = "spring.datasource.hikari.validation-timeout"; @@ -29,14 +29,18 @@ class HikariPoolConstraintValidator implements SmartInitializingSingleton { static final String MAX_LIFETIME_ENV_KEY = "APP_DATASOURCE_POOL_MAX_LIFETIME"; static final String ENV_KEY_PENDING = "env key pending feature-env-driven-runtime-configuration"; - private final Environment environment; - - public HikariPoolConstraintValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; } @Override - public void afterSingletonsInstantiated() { + public String summary() { + return "invalid HikariCP configuration (feature-database-connection-pool-contract D2/D4/D5/D7)"; + } + + @Override + public List violations(Environment environment) { StartupValidationContext violations = StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION); @@ -56,14 +60,17 @@ class HikariPoolConstraintValidator implements SmartInitializingSingleton { } Long connectionTimeout = - parseMillis(CONNECTION_TIMEOUT_KEY, environment.getProperty(CONNECTION_TIMEOUT_KEY)); + parseMillis( + CONNECTION_TIMEOUT_KEY, environment.getProperty(CONNECTION_TIMEOUT_KEY), violations); Long validationTimeout = - parseMillis(VALIDATION_TIMEOUT_KEY, environment.getProperty(VALIDATION_TIMEOUT_KEY)); + parseMillis( + VALIDATION_TIMEOUT_KEY, environment.getProperty(VALIDATION_TIMEOUT_KEY), violations); Long keepaliveTime = - parseMillis(KEEPALIVE_TIME_KEY, environment.getProperty(KEEPALIVE_TIME_KEY)); - Long maxLifetime = parseMillis(MAX_LIFETIME_KEY, environment.getProperty(MAX_LIFETIME_KEY)); + parseMillis(KEEPALIVE_TIME_KEY, environment.getProperty(KEEPALIVE_TIME_KEY), violations); + Long maxLifetime = + parseMillis(MAX_LIFETIME_KEY, environment.getProperty(MAX_LIFETIME_KEY), violations); Long leakDetection = - parseMillis(LEAK_DETECTION_KEY, environment.getProperty(LEAK_DETECTION_KEY)); + parseMillis(LEAK_DETECTION_KEY, environment.getProperty(LEAK_DETECTION_KEY), violations); if (connectionTimeout != null && connectionTimeout < 250L) { violations.reject( @@ -120,28 +127,30 @@ class HikariPoolConstraintValidator implements SmartInitializingSingleton { + leakDetection); } - violations.failIfViolated( - "invalid HikariCP configuration (feature-database-connection-pool-contract D2/D4/D5/D7)"); + return violations.violations(); } /** * Parses the same plain-millisecond, simple Duration ({@code 5s}) and ISO-8601 ({@code PT5S}) * syntax that Spring Boot accepts for Duration-bound properties. A present invalid value is a - * startup error, never an absent-property fallback. + * startup error, never an absent-property fallback: it is recorded as a violation, and the + * constraints that would read it are skipped. * * @return the parsed milliseconds, or {@code null} when absent */ - private static Long parseMillis(String propertyKey, String raw) { + private static Long parseMillis( + String propertyKey, String raw, StartupValidationContext violations) { if (raw == null || raw.isBlank()) { return null; } try { return DurationStyle.detectAndParse(raw.trim(), ChronoUnit.MILLIS).toMillis(); } catch (IllegalArgumentException | ArithmeticException e) { - throw StartupFailures.envValidation( + violations.reject( propertyKey + " must be a valid duration (plain milliseconds, simple duration such as 5s, " + "or ISO-8601 such as PT5S)"); + return null; } } } 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 8ab9ee8e..3825eb6e 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 @@ -58,36 +58,34 @@ class JpaStartupAutoConfiguration { /** Env-validation (exit 78): datasource connection env present before migration runs. */ @Bean - RequiredEnvironmentValidator requiredEnvironmentValidator(Environment environment) { - return new RequiredEnvironmentValidator(environment); + RequiredEnvironmentValidator requiredEnvironmentValidator() { + return new RequiredEnvironmentValidator(); } /** Profile check (exit 71): forbidden Flyway options stay off under the prod profile. */ @Bean - FlywayProdSafetyValidator flywayProdSafetyValidator(Environment environment) { - return new FlywayProdSafetyValidator(environment); + FlywayProdSafetyValidator flywayProdSafetyValidator() { + return new FlywayProdSafetyValidator(); } @Bean - OpenInViewSafetyValidator openInViewSafetyValidator(Environment environment) { - return new OpenInViewSafetyValidator(environment); + OpenInViewSafetyValidator openInViewSafetyValidator() { + return new OpenInViewSafetyValidator(); } @Bean - PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator( - Environment environment) { - return new PostgreSqlTransportSecurityValidator(environment); + PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator() { + return new PostgreSqlTransportSecurityValidator(); } @Bean - PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator( - Environment environment) { - return new PersistenceVendorProdSafetyValidator(environment); + PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator() { + return new PersistenceVendorProdSafetyValidator(); } @Bean - HikariPoolConstraintValidator hikariPoolConstraintValidator(Environment environment) { - return new HikariPoolConstraintValidator(environment); + HikariPoolConstraintValidator hikariPoolConstraintValidator() { + return new HikariPoolConstraintValidator(); } /** The datasource product and version validator. */ diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java index c41d3835..d8f85456 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java @@ -1,7 +1,8 @@ package dev.caskeleton.adapter.outbound.persistence.startup; -import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; -import org.springframework.beans.factory.SmartInitializingSingleton; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import java.util.List; import org.springframework.core.env.Environment; /** @@ -10,32 +11,35 @@ import org.springframework.core.env.Environment; * to Spring Boot's default and only a present {@code true} is rejected. See README for the design * rationale. */ -class OpenInViewSafetyValidator implements SmartInitializingSingleton { +class OpenInViewSafetyValidator implements StartupRule { static final String OPEN_IN_VIEW_KEY = "spring.jpa.open-in-view"; static final String ENV_KEY = "APP_DATASOURCE_OPEN_IN_VIEW"; - private final Environment environment; - - public OpenInViewSafetyValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; } @Override - public void afterSingletonsInstantiated() { + public String summary() { + return ENV_KEY + + " (" + + OPEN_IN_VIEW_KEY + + ") must be false (feature-persistence-failure-baseline D2 — OSIV off baseline)"; + } + + @Override + public List violations(Environment environment) { Boolean openInView = environment.getProperty(OPEN_IN_VIEW_KEY, Boolean.class); - if (Boolean.TRUE.equals(openInView)) { - throw StartupFailures.envValidation( - ENV_KEY - + " (" - + OPEN_IN_VIEW_KEY - + ") must be false " - + "(feature-persistence-failure-baseline D2 — OSIV off baseline): " - + "open-in-view keeps the Hibernate session open through view rendering, " - + "so a lazy association touched in the presentation layer issues a DB query " - + "there, violating the layer boundary. Set " - + ENV_KEY - + "=false."); + if (!Boolean.TRUE.equals(openInView)) { + return List.of(); } + return List.of( + "open-in-view keeps the Hibernate session open through view rendering, " + + "so a lazy association touched in the presentation layer issues a DB query " + + "there, violating the layer boundary. Set " + + ENV_KEY + + "=false."); } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java index 085a64ab..55df08a4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java @@ -1,9 +1,10 @@ package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; +import java.util.List; import java.util.Locale; -import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; /** @@ -30,7 +31,7 @@ import org.springframework.core.env.Environment; *

Scoped to H2 by name rather than asserting "must be PostgreSQL", so a fork that adds a third * production-grade vendor is not blocked by this validator. */ -final class PersistenceVendorProdSafetyValidator implements SmartInitializingSingleton { +final class PersistenceVendorProdSafetyValidator implements StartupRule { static final String VENDOR_KEY = "ca-skeleton.persistence.vendor"; static final String JDBC_URL_KEY = "spring.datasource.url"; @@ -39,32 +40,34 @@ final class PersistenceVendorProdSafetyValidator implements SmartInitializingSin private static final String H2_VENDOR = "h2"; private static final String H2_URL_PREFIX = "jdbc:h2:"; - private final Environment environment; - - public PersistenceVendorProdSafetyValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.PROFILE_CHECK; } @Override - public void afterSingletonsInstantiated() { - if (!RuntimeProfileSnapshot.from(environment).isProduction()) { - return; - } + public String summary() { + return "prod profile forbids the in-memory local datastore"; + } + @Override + public List violations(Environment environment) { + if (!RuntimeProfileSnapshot.from(environment).isProduction()) { + return List.of(); + } String vendor = normalized(environment.getProperty(VENDOR_KEY)); if (H2_VENDOR.equals(vendor)) { - throw StartupFailures.profileMismatch( + return List.of( "prod profile forbids " + VENDOR_KEY + "=h2: the H2 composition is the in-memory local datastore and loses every write" + " when the process restarts"); } - String jdbcUrl = normalized(environment.getProperty(JDBC_URL_KEY)); // The URL is never echoed back — it can carry credentials, endpoints and database names // (same reason as PostgreSqlTransportSecurityValidator). if (jdbcUrl != null && jdbcUrl.startsWith(H2_URL_PREFIX)) { - throw StartupFailures.profileMismatch( + return List.of( "prod profile forbids an H2 datasource: " + JDBC_URL_ENV_KEY + " (" @@ -72,6 +75,7 @@ final class PersistenceVendorProdSafetyValidator implements SmartInitializingSin + ") resolves to a jdbc:h2: URL, which is the in-memory local datastore and also" + " bypasses the prod PostgreSQL TLS check"); } + return List.of(); } private static String normalized(String value) { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java index fbf7f9bb..5acb22b2 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java @@ -1,13 +1,13 @@ package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; /** @@ -16,7 +16,7 @@ import org.springframework.core.env.Environment; *

The validator never includes a JDBC URL in its failure because URLs can carry credentials, * endpoints, and database names. */ -final class PostgreSqlTransportSecurityValidator implements SmartInitializingSingleton { +final class PostgreSqlTransportSecurityValidator implements StartupRule { static final String JDBC_URL_KEY = "spring.datasource.url"; static final String JDBC_URL_ENV_KEY = "APP_DATASOURCE_URL"; @@ -27,36 +27,38 @@ final class PostgreSqlTransportSecurityValidator implements SmartInitializingSin private static final String VERIFY_FULL = "verify-full"; private static final Pattern URL_SSLMODE = Pattern.compile("(?i)(?:[?&])sslmode=([^&]*)"); - private final Environment environment; - - public PostgreSqlTransportSecurityValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.PROFILE_CHECK; } @Override - public void afterSingletonsInstantiated() { - if (!RuntimeProfileSnapshot.from(environment).isProduction()) { - return; - } + public String summary() { + return "prod PostgreSQL transport security is not verified"; + } + @Override + public List violations(Environment environment) { + if (!RuntimeProfileSnapshot.from(environment).isProduction()) { + return List.of(); + } String jdbcUrl = environment.getProperty(JDBC_URL_KEY); if (jdbcUrl == null || !jdbcUrl.trim().toLowerCase(Locale.ROOT).startsWith(POSTGRESQL_PREFIX)) { - return; + return List.of(); } - List urlModes = urlSslModes(jdbcUrl); String propertyMode = normalized(environment.getProperty(HIKARI_SSLMODE_KEY)); + // The first finding only, as before: each one makes the next meaningless. if (urlModes.size() > 1) { - reject("prod PostgreSQL transport has ambiguous duplicate sslmode declarations"); + return List.of("prod PostgreSQL transport has ambiguous duplicate sslmode declarations"); } String urlMode = urlModes.isEmpty() ? null : urlModes.getFirst(); if (urlMode != null && propertyMode != null && !urlMode.equals(propertyMode)) { - reject("prod PostgreSQL transport has conflicting sslmode declarations"); + return List.of("prod PostgreSQL transport has conflicting sslmode declarations"); } - String effectiveMode = propertyMode != null ? propertyMode : urlMode; if (!VERIFY_FULL.equals(effectiveMode)) { - reject( + return List.of( "prod PostgreSQL transport requires pgJDBC sslmode=verify-full through " + JDBC_URL_ENV_KEY + " (" @@ -64,6 +66,7 @@ final class PostgreSqlTransportSecurityValidator implements SmartInitializingSin + ") or " + HIKARI_SSLMODE_KEY); } + return List.of(); } private static List urlSslModes(String jdbcUrl) { @@ -78,8 +81,4 @@ final class PostgreSqlTransportSecurityValidator implements SmartInitializingSin private static String normalized(String value) { return value == null ? null : value.trim().toLowerCase(Locale.ROOT); } - - private static void reject(String message) { - throw StartupFailures.profileMismatch(message); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java index 4df50014..8f065c5d 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java @@ -1,9 +1,9 @@ package dev.caskeleton.adapter.outbound.persistence.startup; 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 java.util.List; import java.util.Map; -import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; /** @@ -11,37 +11,36 @@ import org.springframework.core.env.Environment; * migration fails with an opaque driver error. Absent or blank counts as missing. See README for * the design rationale. */ -class RequiredEnvironmentValidator implements SmartInitializingSingleton { +class RequiredEnvironmentValidator implements StartupRule { - /** Spring property key → operator-facing env key (named in the failure message). */ static final Map REQUIRED_DATASOURCE_ENV = Map.of( "spring.datasource.url", "APP_DATASOURCE_URL", "spring.datasource.username", "APP_DATASOURCE_USERNAME", "spring.datasource.driver-class-name", "APP_DATASOURCE_DRIVER"); - private final Environment environment; - - public RequiredEnvironmentValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; } @Override - public void afterSingletonsInstantiated() { - StartupValidationContext missing = - StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION); + public String summary() { + return "required datasource environment is missing or blank — a Flyway migration" + + " cannot run without it"; + } + + @Override + public List violations(Environment environment) { // Sorted for a stable, deterministic message regardless of map iteration order. - REQUIRED_DATASOURCE_ENV.entrySet().stream() + return REQUIRED_DATASOURCE_ENV.entrySet().stream() .sorted(Map.Entry.comparingByValue()) - .forEach( + .filter( entry -> { String value = environment.getProperty(entry.getKey()); - if (value == null || value.isBlank()) { - missing.reject(entry.getValue() + " (" + entry.getKey() + ")"); - } - }); - missing.failIfViolated( - "required datasource environment is missing or blank — a Flyway migration" - + " cannot run without it"); + return value == null || value.isBlank(); + }) + .map(entry -> entry.getValue() + " (" + entry.getKey() + ")") + .toList(); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java index c2d49941..39ead9d6 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java @@ -4,6 +4,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.Test; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -21,7 +22,8 @@ import org.springframework.core.env.Environment; class FlywayProdSafetyValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @Test void prodProfileWithPinnedSafeDefaultsStartsCleanly() { @@ -110,7 +112,7 @@ class FlywayProdSafetyValidatorTest { static class ValidatorConfig { @Bean FlywayProdSafetyValidator flywayProdSafetyValidator(Environment environment) { - return new FlywayProdSafetyValidator(environment); + return new FlywayProdSafetyValidator(); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java index 397c963c..b919ffba 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 @@ -4,6 +4,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.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -18,7 +19,8 @@ import org.springframework.core.env.Environment; class HikariPoolConstraintValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); // --- D2 / HIKARI-CFG-C1: connection-timeout >= 250 --- @@ -265,7 +267,7 @@ class HikariPoolConstraintValidatorTest { static class ValidatorConfig { @Bean HikariPoolConstraintValidator hikariPoolConstraintValidator(Environment environment) { - return new HikariPoolConstraintValidator(environment); + return new HikariPoolConstraintValidator(); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java index 6e690bf4..fcf871f6 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java @@ -4,6 +4,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.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -19,7 +20,8 @@ import org.springframework.core.env.Environment; class OpenInViewSafetyValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @Test void openInViewTrueFailsStartupNamingTheAppKey() { @@ -71,7 +73,7 @@ class OpenInViewSafetyValidatorTest { static class ValidatorConfig { @Bean OpenInViewSafetyValidator openInViewSafetyValidator(Environment environment) { - return new OpenInViewSafetyValidator(environment); + return new OpenInViewSafetyValidator(); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java index 5f3f9a59..46b078b5 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java @@ -4,6 +4,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 java.io.PrintWriter; import java.io.StringWriter; import org.junit.jupiter.api.Test; @@ -20,7 +21,8 @@ class PersistenceVendorProdSafetyValidatorTest { private static final String H2_URL = "jdbc:h2:mem:ca_skeleton;MODE=PostgreSQL"; private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @ParameterizedTest @ValueSource(strings = {"h2", "H2", " h2 "}) @@ -100,7 +102,7 @@ class PersistenceVendorProdSafetyValidatorTest { @Bean PersistenceVendorProdSafetyValidator validator(Environment environment) { - return new PersistenceVendorProdSafetyValidator(environment); + return new PersistenceVendorProdSafetyValidator(); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java index c00a5f0d..e012f579 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java @@ -4,6 +4,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 java.io.PrintWriter; import java.io.StringWriter; import org.junit.jupiter.api.Test; @@ -17,7 +18,8 @@ import org.springframework.core.env.Environment; class PostgreSqlTransportSecurityValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @ParameterizedTest @ValueSource( @@ -102,7 +104,7 @@ class PostgreSqlTransportSecurityValidatorTest { @Bean PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator( Environment environment) { - return new PostgreSqlTransportSecurityValidator(environment); + return new PostgreSqlTransportSecurityValidator(); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java index be16fa9c..2552d2c2 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java @@ -4,6 +4,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.Test; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -20,7 +21,8 @@ import org.springframework.core.env.Environment; class RequiredEnvironmentValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @Test void allDatasourceEnvPresentStartsCleanly() { @@ -80,7 +82,7 @@ class RequiredEnvironmentValidatorTest { static class ValidatorConfig { @Bean RequiredEnvironmentValidator requiredEnvironmentValidator(Environment environment) { - return new RequiredEnvironmentValidator(environment); + return new RequiredEnvironmentValidator(); } } } diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisDeploymentMode.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisDeploymentMode.java similarity index 91% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisDeploymentMode.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisDeploymentMode.java index 85f42229..3d6c4d2e 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisDeploymentMode.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisDeploymentMode.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api; +package dev.caskeleton.adapter.outbound.cache.redis.runtime; -/** Redis deployment topology the SDK is bound to. */ +/** Redis deployment topology the runtime's client is bound to. */ public enum RedisDeploymentMode { /** Single primary, optional replicas, any database index. */ STANDALONE, diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculator.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/cluster/RedisSlotCalculator.java similarity index 97% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculator.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/cluster/RedisSlotCalculator.java index 3c5ad12b..73742472 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculator.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/cluster/RedisSlotCalculator.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster; import java.nio.charset.StandardCharsets; import java.util.Objects; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/LettuceSemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/LettuceSemanticRedisCommands.java new file mode 100644 index 00000000..aa126f75 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/LettuceSemanticRedisCommands.java @@ -0,0 +1,91 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.command; + +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.SetArgs; +import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletionStage; + +/** + * {@link SemanticRedisCommands} on a Lettuce connection. + * + *

Bound to {@code byte[]} keys and values: rendering and encoding happened in the caller, so + * nothing here can reinterpret a key or pick a codec. + */ +public final class LettuceSemanticRedisCommands implements SemanticRedisCommands { + + private static final String OK = "OK"; + + private final RedisClusterAsyncCommands commands; + + /** + * Creates the commands over a connection's asynchronous surface. + * + * @param commands the standalone or slot-routing asynchronous commands of one connection + */ + public LettuceSemanticRedisCommands(RedisClusterAsyncCommands commands) { + this.commands = Objects.requireNonNull(commands, "commands must be non-null"); + } + + @Override + public CompletionStage get(byte[] key) { + return commands.get(key); + } + + @Override + public CompletionStage set( + byte[] key, byte[] value, WritePresence presence, Duration ttl) { + Objects.requireNonNull(ttl, "ttl must be non-null"); + if (ttl.isZero() || ttl.isNegative()) { + throw new IllegalArgumentException("ttl must be positive"); + } + SetArgs arguments = + switch (presence) { + case IF_ABSENT -> new SetArgs().nx(); + case IF_PRESENT -> new SetArgs().xx(); + case ALWAYS -> new SetArgs(); + }; + return commands.set(key, value, arguments.px(ttl)).thenApply(OK::equals); + } + + @Override + public CompletionStage getAndDelete(byte[] key) { + return commands.getdel(key); + } + + @Override + public CompletionStage incrementBy(byte[] key, long delta) { + return commands.incrby(key, delta); + } + + @Override + public CompletionStage ping() { + return commands.ping(); + } + + @Override + public CompletionStage loadScript(byte[] source) { + return commands.scriptLoad(source); + } + + @Override + public CompletionStage> evaluateRegisteredForList( + String digest, byte[] key, List arguments) { + return commands + .>evalsha( + digest, ScriptOutputType.MULTI, new byte[][] {key}, arguments.toArray(byte[][]::new)) + .thenApply(reply -> reply == null ? List.of() : reply); + } + + @Override + public CompletionStage evaluateRegisteredForLong( + String digest, byte[] key, List arguments) { + RedisFuture reply = + commands.evalsha( + digest, ScriptOutputType.INTEGER, new byte[][] {key}, arguments.toArray(byte[][]::new)); + return reply; + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/SemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/SemanticRedisCommands.java new file mode 100644 index 00000000..70c4e46a --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/SemanticRedisCommands.java @@ -0,0 +1,96 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.command; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletionStage; + +/** + * The commands the runtime's own consumers send: the semantic adapters in {@code cache-redis} and + * the health contributor. + * + *

Eight commands and no more. The runtime used to hand every lane a gateway carrying the typed + * SDK's whole surface — about 118 commands, raw and admin paths included — so a leaf that needed a + * cache read and a script call compiled against streams, geo and cluster admin. The rest of that + * surface is the typed SDK's own ({@code redis-sdk}), which extends this interface rather than the + * runtime carrying it on the SDK's behalf. + * + *

Keys and values are already rendered and encoded. Nothing here picks a codec or a key. + */ +public interface SemanticRedisCommands { + + /** + * Reads a value. + * + * @param key the rendered key + * @return the stored bytes, {@code null} when the key does not exist + */ + CompletionStage get(byte[] key); + + /** + * Writes a value with an existence condition and a relative expiry, as one command. + * + * @param key the rendered key + * @param value the encoded value + * @param presence the existence condition + * @param ttl the positive time to live the write carries + * @return whether the write was applied + */ + CompletionStage set(byte[] key, byte[] value, WritePresence presence, Duration ttl); + + /** + * Reads and removes a value as one command. + * + * @param key the rendered key + * @return the removed bytes, {@code null} when the key did not exist + */ + CompletionStage getAndDelete(byte[] key); + + /** + * Increments an integer counter without touching its expiry. + * + * @param key the rendered key + * @param delta the increment + * @return the value after the increment + */ + CompletionStage incrementBy(byte[] key, long delta); + + /** + * Sends a keyless liveness round trip. + * + *

Keyless on purpose: a probe that touched a key would be subject to the ACL key pattern and + * report "unhealthy" for reasons that have nothing to do with reachability. + * + * @return the server's reply + */ + CompletionStage ping(); + + /** + * Registers a script and returns its digest. + * + * @param source the script source + * @return the digest the server assigned + */ + CompletionStage loadScript(byte[] source); + + /** + * Evaluates a registered single-key script whose reply is an array. + * + * @param digest the loaded script digest + * @param key the single key the script touches + * @param arguments the script arguments + * @return the reply values + */ + CompletionStage> evaluateRegisteredForList( + String digest, byte[] key, List arguments); + + /** + * Evaluates a registered single-key script whose reply is an integer. + * + * @param digest the loaded script digest + * @param key the single key the script touches + * @param arguments the script arguments + * @return the integer reply + */ + CompletionStage evaluateRegisteredForLong( + String digest, byte[] key, List arguments); +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/WritePresence.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/WritePresence.java similarity index 85% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/WritePresence.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/WritePresence.java index faf060a8..9b49993c 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/WritePresence.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/WritePresence.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.command; /** * The existence condition a {@code SET} carries. diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisAccountContribution.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisAccountContribution.java new file mode 100644 index 00000000..3f2a8bb1 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisAccountContribution.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import java.util.Objects; + +/** + * An account another module's lanes authenticate as, and where its credential comes from. + * + *

Declared as a bean by the module (or the service) that composes the lanes. {@link + * RedisRuntimeAutoConfiguration} resolves the reference through the same secret source as its own + * accounts, before any client exists, and builds a client authenticated as it. A reference that + * does not resolve fails startup rather than the first command. + * + * @param account the account + * @param credentialReference the credential reference, in the runtime's {@code secret://} form + */ +public record RedisAccountContribution(RedisAccount account, String credentialReference) { + + public RedisAccountContribution { + Objects.requireNonNull(account, "account must be non-null"); + if (RedisAccount.APPLICATION.equals(account) || RedisAccount.ADVANCED.equals(account)) { + throw new IllegalArgumentException( + "the " + account + " account is the runtime's own and is configured in app.redis"); + } + if (credentialReference == null || credentialReference.isBlank()) { + throw new IllegalArgumentException( + "the " + account + " account needs a credential reference"); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRequirement.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRequirement.java new file mode 100644 index 00000000..704eb1e7 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRequirement.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import org.springframework.core.env.Environment; + +/** + * A module's answer to "does this deployment need Redis for correctness?". + * + *

Registered under this interface's name in {@code META-INF/spring.factories} by the module that + * owns the roles, and read through {@link RedisCorrectnessRoles}. Implementations need a public + * no-argument constructor and must decide from the environment alone: they run before any bean + * exists. + */ +public interface RedisCorrectnessRequirement { + + /** + * Reports whether a role this module owns selected Redis for correctness. + * + * @param environment the resolved environment + * @return {@code true} when readiness must gate on Redis + */ + boolean required(Environment environment); + + /** + * Reports whether such a role runs registered scripts on the SCRIPT lane. + * + * @param environment the resolved environment + * @return {@code true} when the SCRIPT lane carries a correctness role + */ + boolean requiresScriptLane(Environment environment); +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRoles.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRoles.java new file mode 100644 index 00000000..a0023d69 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCorrectnessRoles.java @@ -0,0 +1,65 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import java.util.List; +import org.springframework.core.env.Environment; +import org.springframework.core.io.support.SpringFactoriesLoader; + +/** + * Whether this deployment needs Redis for correctness rather than for speed. + * + *

A role such as idempotency or rate limiting produces a wrong answer when Redis is gone, not a + * slow one, so a deployment that selected one gates its readiness on Redis. A cache does not — its + * outage is degradation. + * + *

The runtime does not know which roles exist or how they are selected: that belongs to the + * modules that implement them (for the semantic ports, {@code cache-redis}). Each such module + * registers a {@link RedisCorrectnessRequirement} in {@code META-INF/spring.factories}, and this + * class only asks them. Environment post-processors run before any bean exists, and the readiness + * group must be decided there, so a factories entry rather than a bean is the one mechanism both + * readers can use. + * + *

The question is asked in two places that must never disagree: the condition that creates the + * {@code redisRequired} contributor, and the post-processor that lets the readiness group name it. + * When those drifted apart every Redis-off deployment failed at startup with {@code Included health + * contributor 'redisRequired' in group 'readiness' does not exist}. One predicate, two readers. + */ +public final class RedisCorrectnessRoles { + + /** The bean name of the readiness-gating health contributor. */ + public static final String REQUIRED_HEALTH_CONTRIBUTOR = "redisRequired"; + + /** The bean name of the degradation-only health contributor. */ + public static final String OPTIONAL_HEALTH_CONTRIBUTOR = "redisOptional"; + + private RedisCorrectnessRoles() { + throw new AssertionError("RedisCorrectnessRoles is a constant holder"); + } + + /** + * Reports whether any registered module needs Redis for correctness in this environment. + * + * @param environment the resolved environment + * @return {@code true} when readiness must gate on Redis + */ + public static boolean anySelected(Environment environment) { + return requirements().stream().anyMatch(requirement -> requirement.required(environment)); + } + + /** + * Reports whether a correctness role that runs registered scripts is selected, so the SCRIPT lane + * — which authenticates as the advanced account — has to be probed as well. + * + * @param environment the resolved environment + * @return {@code true} when the SCRIPT lane carries a correctness role + */ + public static boolean anyScriptRoleSelected(Environment environment) { + return requirements().stream() + .anyMatch(requirement -> requirement.requiresScriptLane(environment)); + } + + private static List requirements() { + return SpringFactoriesLoader.forDefaultResourceLocation( + RedisCorrectnessRoles.class.getClassLoader()) + .load(RedisCorrectnessRequirement.class); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCredentialResolver.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCredentialResolver.java similarity index 98% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCredentialResolver.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCredentialResolver.java index 929a59fa..eea6dc88 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCredentialResolver.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisCredentialResolver.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import java.util.Objects; import java.util.Optional; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisHealthContributor.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java similarity index 90% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisHealthContributor.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java index 86ccad79..aee4fb09 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisHealthContributor.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributor.java @@ -1,9 +1,9 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +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 java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.LinkedHashMap; @@ -87,25 +87,25 @@ public final class RedisHealthContributor { // A round trip, not a flag. `isOpen()` on a driver connection reports what the client // believes, which stays true for as long as it takes TCP to notice — the window in which a // health check is most likely to be wrong is exactly the window it exists to catch. - reply = lease.gateway().ping().toCompletableFuture().get(nanos(), TimeUnit.NANOSECONDS); + reply = lease.commands().ping().toCompletableFuture().get(nanos(), TimeUnit.NANOSECONDS); } if (scriptProbeKey.isPresent()) { try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { String digest = lease - .gateway() + .commands() .loadScript(SCRIPT_PROBE) .toCompletableFuture() .get(nanos(), TimeUnit.NANOSECONDS); lease - .gateway() + .commands() .evaluateRegisteredForLong(digest, scriptProbeKey.get(), List.of()) .toCompletableFuture() .get(nanos(), TimeUnit.NANOSECONDS); } } return new RedisHealth(true, detail("reachable", String.valueOf(reply))); - } catch (RedisCommandRejectedException refused) { + } catch (RedisLaneUnavailableException refused) { // A refusal is raised before any command exists: either shutdown began, or the lane is full. return owner.state() != RedisRuntimeOwner.State.OPEN ? shuttingDown() diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneContribution.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneContribution.java new file mode 100644 index 00000000..f2e5b642 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisLaneContribution.java @@ -0,0 +1,25 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import java.util.Objects; + +/** + * A lane another module composes on the runtime, and its connection ceiling. + * + *

Declared as a bean by the module (or the service) that uses the lane; {@link + * RedisRuntimeAutoConfiguration} pools and drains it with the runtime's own lanes. The runtime + * knows nothing about a contributed lane beyond its account and ceiling. + * + * @param lane the lane + * @param maximumConnections how many connections the lane may hold at once + */ +public record RedisLaneContribution(RedisLane lane, int maximumConnections) { + + public RedisLaneContribution { + Objects.requireNonNull(lane, "lane must be non-null"); + if (maximumConnections < 1) { + throw new IllegalArgumentException( + "connection lane " + lane.name() + " needs a positive ceiling"); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java similarity index 74% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java index 9e4bc9d7..9dfabc89 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfiguration.java @@ -1,13 +1,14 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisCredentialRole; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisTopologyClientFactory; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisTopologyClientFactory; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.nio.charset.StandardCharsets; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -34,7 +35,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata; * The Redis composition root, and the only place Redis settings come into existence. * *

{@code app.redis.enabled} is the whole switch. While it is false this class contributes - * nothing, and because {@link RedisSdkSettings} is registered here rather than by the + * nothing, and because {@link RedisRuntimeSettings} is registered here rather than by the * application-wide {@code @ConfigurationPropertiesScan}, "contributes nothing" is literal: the * properties are not bound, the cross-field rules are not run, no credential is resolved, and no * policy resource, TLS material, client, connection or thread is created. A deployment that does @@ -43,7 +44,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata; * *

While it is true the order is fixed and entirely local: bind, validate, then build. Validation * runs at context refresh, before anything can reach the network, which is what makes {@link - * RedisSdkSettings#validate()} the fail-fast its own documentation claims — until this class + * RedisRuntimeSettings#validate()} the fail-fast its own documentation claims — until this class * existed the method had no production caller at all. * *

Roles — cache, session, idempotency, rate limiting, leases — select which Redis @@ -56,9 +57,9 @@ import org.springframework.core.type.AnnotatedTypeMetadata; // Without it the bean is created and silently left at its defaults, which is worse than not // binding at all: validation would pass on settings nobody configured. @EnableConfigurationProperties -public class RedisSdkAutoConfiguration { +public class RedisRuntimeAutoConfiguration { - private static final Logger LOG = LoggerFactory.getLogger(RedisSdkAutoConfiguration.class); + private static final Logger LOG = LoggerFactory.getLogger(RedisRuntimeAutoConfiguration.class); /** * The status an optional Redis reports when it is unreachable. @@ -82,15 +83,15 @@ public class RedisSdkAutoConfiguration { */ @Bean @ConfigurationProperties(prefix = "app.redis") - public RedisSdkSettings redisSdkSettings() { - return new RedisSdkSettings(); + public RedisRuntimeSettings redisRuntimeSettings() { + return new RedisRuntimeSettings(); } /** * Runs the cross-field rules once the binder has populated the settings. * *

Spring binds {@code @ConfigurationProperties} after the factory method returns, so the - * validation cannot live inside {@link #redisSdkSettings()}. A {@code + * validation cannot live inside {@link #redisRuntimeSettings()}. A {@code * ConfigurationPropertiesBindHandlerAdvisor}-free way to get the same fail-fast is a bean that * depends on the settings: it is created during refresh, before any Redis client would be, and an * exception here stops the context. @@ -99,10 +100,11 @@ public class RedisSdkAutoConfiguration { * @return the validation outcome, kept as a bean so warnings are inspectable in tests */ @Bean - public RedisSdkSettingsValidation redisSdkSettingsValidation(RedisSdkSettings settings) { + public RedisRuntimeSettingsValidation redisRuntimeSettingsValidation( + RedisRuntimeSettings settings) { List warnings = settings.validate(); - warnings.forEach(warning -> LOG.warn("Redis SDK configuration warning: {}", warning)); - return new RedisSdkSettingsValidation(warnings); + warnings.forEach(warning -> LOG.warn("Redis configuration warning: {}", warning)); + return new RedisRuntimeSettingsValidation(warnings); } /** @@ -114,58 +116,60 @@ public class RedisSdkAutoConfiguration { * * @param settings the validated settings * @param secretSource resolves a secret name to its value + * @param contributedAccounts accounts a module composing lanes on the runtime asked for * @param validation ordered after validation so a malformed setting is reported first * @return the resolved credentials */ @Bean public RedisResolvedCredentials redisResolvedCredentials( - RedisSdkSettings settings, + RedisRuntimeSettings settings, ObjectProvider secretSource, - RedisSdkSettingsValidation validation) { + ObjectProvider contributedAccounts, + RedisRuntimeSettingsValidation validation) { RedisCredentialResolver resolver = new RedisCredentialResolver( name -> secretSource.getIfAvailable(() -> environmentSecretSource()).resolve(name)); - Map accounts = - new EnumMap<>(RedisCredentialRole.class); - // Every configured role is resolved, not only the application one. A deployment that named an - // advanced or pub/sub account and got a client that silently authenticated as the application - // account has the privilege separation it configured on paper and nowhere else. + Map accounts = new LinkedHashMap<>(); + // Every configured account is resolved, not only the application one. A deployment that named + // an advanced account and got a client that silently authenticated as the application account + // has the privilege separation it configured on paper and nowhere else. put( accounts, - RedisCredentialRole.APPLICATION, + RedisAccount.APPLICATION, resolver.resolve("application", settings.getAuthentication().getCredentialReference())); put( accounts, - RedisCredentialRole.ADVANCED, + RedisAccount.ADVANCED, resolver.resolve( "advanced", settings.getAuthentication().getAdvancedCredentialReference())); - put( - accounts, - RedisCredentialRole.PUBSUB, - resolver.resolve("pub/sub", settings.getAuthentication().getPubsubCredentialReference())); - if (settings.getAdmin().isEnabled()) { - put( - accounts, - RedisCredentialRole.ADMIN, - resolver.resolve("admin", settings.getAdmin().getCredentialReference())); - } + // A module that composes lanes on the runtime (the typed SDK's admin plane) names its own + // account; the runtime resolves it exactly like its own, before any client exists. + contributedAccounts + .orderedStream() + .forEach( + contribution -> + put( + accounts, + contribution.account(), + resolver.resolve( + contribution.account().name(), contribution.credentialReference()))); Optional sentinel = settings.getMode() - == dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode.SENTINEL + == dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode.SENTINEL ? resolver.resolve("sentinel", settings.getSentinel().getCredentialReference()) : Optional.empty(); LOG.info( - "Redis accounts resolved for roles {}{}", + "Redis accounts resolved: {}{}", accounts.keySet(), sentinel.isPresent() ? " plus the Sentinel control account" : ""); return new RedisResolvedCredentials(accounts, sentinel); } private static void put( - Map accounts, - RedisCredentialRole role, + Map accounts, + RedisAccount account, Optional resolved) { - resolved.ifPresent(credentials -> accounts.put(role, credentials)); + resolved.ifPresent(credentials -> accounts.put(account, credentials)); } private static RedisSecretSource environmentSecretSource() { @@ -183,7 +187,7 @@ public class RedisSdkAutoConfiguration { */ @Bean public RedisRuntimeClient redisRuntimeClient( - RedisSdkSettings settings, + RedisRuntimeSettings settings, RedisResolvedCredentials credentials, ResourceLoader resourceLoader) { return new RedisTopologyClientFactory( @@ -224,20 +228,33 @@ public class RedisSdkAutoConfiguration { *

Destroyed by Spring, and destroyed before the client bean it wraps because it depends on it * — which is the order shutdown needs: connections drain and close, then the event loop stops. * + *

The runtime's own lanes take their ceilings from the settings. A module that composes + * further lanes on the runtime contributes their ceilings as {@link RedisLaneContribution} beans; + * the runtime pools and drains those exactly like its own, and knows nothing else about them. + * * @param client the runtime client * @param settings the validated settings + * @param contributedLanes lanes other modules compose on the runtime * @return the lifecycle owner */ @Bean(destroyMethod = "close") - public RedisRuntimeOwner redisRuntimeOwner(RedisRuntimeClient client, RedisSdkSettings settings) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + public RedisRuntimeOwner redisRuntimeOwner( + RedisRuntimeClient client, + RedisRuntimeSettings settings, + ObjectProvider contributedLanes) { + Map limits = new LinkedHashMap<>(); limits.put(RedisConnectionKind.REGULAR, settings.getCapacity().getMaximumInFlightCommands()); - limits.put(RedisConnectionKind.BLOCKING, settings.getBlocking().getMaxConnections()); - limits.put(RedisConnectionKind.TRANSACTION, settings.getTransaction().getMaxConnections()); limits.put(RedisConnectionKind.SCRIPT, settings.getCapacity().getMaximumScriptConnections()); - limits.put( - RedisConnectionKind.PUBSUB, Math.max(1, settings.getPubsub().getBufferCapacity() / 64)); - limits.put(RedisConnectionKind.ADMIN, settings.getAdmin().isEnabled() ? 2 : 1); + contributedLanes + .orderedStream() + .forEach( + contribution -> { + if (limits.putIfAbsent(contribution.lane(), contribution.maximumConnections()) + != null) { + throw new IllegalStateException( + "Redis lane " + contribution.lane().name() + " was composed twice"); + } + }); return new RedisRuntimeOwner( client, limits, @@ -257,7 +274,7 @@ public class RedisSdkAutoConfiguration { * @return the contributor */ @Bean(RedisCorrectnessRoles.OPTIONAL_HEALTH_CONTRIBUTOR) - public HealthIndicator redisOptional(RedisRuntimeOwner owner, RedisSdkSettings settings) { + public HealthIndicator redisOptional(RedisRuntimeOwner owner, RedisRuntimeSettings settings) { RedisHealthContributor contributor = new RedisHealthContributor(owner, settings.getTimeout().getFast()); return () -> { @@ -291,7 +308,7 @@ public class RedisSdkAutoConfiguration { @Bean(RedisCorrectnessRoles.REQUIRED_HEALTH_CONTRIBUTOR) @Conditional(RedisCorrectnessRoleBound.class) public HealthIndicator redisRequired( - RedisRuntimeOwner owner, RedisSdkSettings settings, Environment environment) { + RedisRuntimeOwner owner, RedisRuntimeSettings settings, Environment environment) { Optional scriptProbeKey = RedisCorrectnessRoles.anyScriptRoleSelected(environment) ? Optional.of( @@ -331,17 +348,17 @@ public class RedisSdkAutoConfiguration { } /** - * The account resolved for each role the configuration named. + * The credentials resolved for each account the configuration named. * - *

A role that is absent from {@code accounts} has no account of its own and runs on the - * application client. That is a deployment decision, taken by not configuring one, rather than a - * default the SDK picks. + *

An account that is absent from {@code accounts} has no credentials of its own and its lanes + * run on the application client. That is a deployment decision, taken by not configuring one, + * rather than a default the runtime picks. * - * @param accounts the resolved account per configured role + * @param accounts the resolved credentials per configured account * @param sentinel the Sentinel control account, on a Sentinel deployment */ public record RedisResolvedCredentials( - Map accounts, + Map accounts, Optional sentinel) { public RedisResolvedCredentials { @@ -367,9 +384,9 @@ public class RedisSdkAutoConfiguration { * * @param warnings settings that are within the guardrails but worth an operator's attention */ - public record RedisSdkSettingsValidation(List warnings) { + public record RedisRuntimeSettingsValidation(List warnings) { - public RedisSdkSettingsValidation { + public RedisRuntimeSettingsValidation { warnings = List.copyOf(warnings); } } diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeSettings.java similarity index 84% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeSettings.java index 4b704ce9..41072e40 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeSettings.java @@ -1,13 +1,17 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** - * Typed configuration for the Redis SDK, bound from {@code app.redis.*}. + * Typed configuration for the Redis runtime, bound from {@code app.redis.*}. + * + *

Topology, accounts, TLS, lifecycle and the ceilings of the runtime's own lanes. The typed + * SDK's lanes (blocking, transaction, admin) are not configured here: a module that composes lanes + * on the runtime brings their limits and accounts with it. * *

Defaults are the skeleton guardrails from the design. Validation is fail-closed and runs at * startup: a setting that would make a guardrail meaningless — a non-zero database on Cluster, an @@ -15,12 +19,12 @@ import java.util.List; * degrading quietly at the first request. * *

This class carries no {@code @ConfigurationProperties} annotation on purpose. It is registered - * and bound only by {@link RedisSdkAutoConfiguration}, which exists only while {@code + * and bound only by {@link RedisRuntimeAutoConfiguration}, which exists only while {@code * app.redis.enabled} is true. Annotating the class would put it back inside the application-wide * {@code @ConfigurationPropertiesScan}, and a Redis-free deployment would once again bind Redis * configuration — the exact defect this arrangement removes. */ -public class RedisSdkSettings { +public class RedisRuntimeSettings { /** Hard ceiling above which a configured timeout is a startup failure. */ public static final Duration MAXIMUM_TIMEOUT = Duration.ofSeconds(30); @@ -34,16 +38,12 @@ public class RedisSdkSettings { private int database; private final Namespace namespace = new Namespace(); private final Timeouts timeout = new Timeouts(); - private final Blocking blocking = new Blocking(); - private final Transaction transaction = new Transaction(); private final Authentication authentication = new Authentication(); private final Sentinel sentinel = new Sentinel(); private final Tls tls = new Tls(); private final Lifecycle lifecycle = new Lifecycle(); private final Cluster cluster = new Cluster(); private final Capacity capacity = new Capacity(); - private final PubSub pubsub = new PubSub(); - private final Admin admin = new Admin(); /** * Validates every cross-field rule. @@ -66,9 +66,6 @@ public class RedisSdkSettings { validateTimeout("fast", timeout.getFast(), warnings); validateTimeout("script", timeout.getScript(), warnings); validateTimeout("batch", timeout.getBatch(), warnings); - if (blocking.getMaxConnections() < 1 || transaction.getMaxConnections() < 1) { - throw new IllegalStateException("dedicated connection lanes need a positive ceiling"); - } if (mode == RedisDeploymentMode.SENTINEL && (sentinel.getMasterName() == null || sentinel.getMasterName().isBlank())) { throw new IllegalStateException( @@ -95,13 +92,6 @@ public class RedisSdkSettings { lifecycle.validate(); capacity.validate(); cluster.validate(); - pubsub.validate(); - if (admin.isEnabled() - && (admin.getCredentialReference() == null || admin.getCredentialReference().isBlank())) { - throw new IllegalStateException( - "app.redis.admin.credential-reference is required when app.redis.admin.enabled=true: the" - + " admin plane authenticates as its own account"); - } // Last, deliberately. A deployment with both a structural mistake and a missing credential // should be told about the structural one first: it is the cheaper thing to be wrong about, // and reporting "no credential" for a configuration that could never have connected anyway @@ -194,40 +184,11 @@ public class RedisSdkSettings { } } - /** Blocking lane ceilings. */ - public static class Blocking { - - private int maxConnections = 32; - - public int getMaxConnections() { - return maxConnections; - } - - public void setMaxConnections(int maxConnections) { - this.maxConnections = maxConnections; - } - } - - /** Transaction lane ceilings. */ - public static class Transaction { - - private int maxConnections = 16; - - public int getMaxConnections() { - return maxConnections; - } - - public void setMaxConnections(int maxConnections) { - this.maxConnections = maxConnections; - } - } - /** Application authentication material, carried as references rather than values. */ public static class Authentication { private String credentialReference; private String advancedCredentialReference; - private String pubsubCredentialReference; private boolean anonymousAccessAccepted; void validate(List warnings) { @@ -289,14 +250,6 @@ public class RedisSdkSettings { public void setAdvancedCredentialReference(String advancedCredentialReference) { this.advancedCredentialReference = advancedCredentialReference; } - - public String getPubsubCredentialReference() { - return pubsubCredentialReference; - } - - public void setPubsubCredentialReference(String pubsubCredentialReference) { - this.pubsubCredentialReference = pubsubCredentialReference; - } } /** Sentinel discovery. */ @@ -545,49 +498,6 @@ public class RedisSdkSettings { } } - /** Subscription delivery. */ - public static class PubSub { - - private int bufferCapacity = 1_024; - - void validate() { - if (bufferCapacity < 1) { - throw new IllegalStateException("the pub/sub buffer capacity must be positive"); - } - } - - public int getBufferCapacity() { - return bufferCapacity; - } - - public void setBufferCapacity(int bufferCapacity) { - this.bufferCapacity = bufferCapacity; - } - } - - /** Isolated admin plane exposure. */ - public static class Admin { - - private boolean enabled; - private String credentialReference; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getCredentialReference() { - return credentialReference; - } - - public void setCredentialReference(String credentialReference) { - this.credentialReference = credentialReference; - } - } - public boolean isEnabled() { return enabled; } @@ -628,18 +538,6 @@ public class RedisSdkSettings { return timeout; } - public Blocking getBlocking() { - return blocking; - } - - public Transaction getTransaction() { - return transaction; - } - - public Admin getAdmin() { - return admin; - } - public Authentication getAuthentication() { return authentication; } @@ -663,8 +561,4 @@ public class RedisSdkSettings { public Capacity getCapacity() { return capacity; } - - public PubSub getPubsub() { - return pubsub; - } } diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/AccountRoutingRuntimeClient.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/AccountRoutingRuntimeClient.java new file mode 100644 index 00000000..a8d5794b --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/AccountRoutingRuntimeClient.java @@ -0,0 +1,66 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Routes each lane to the client that authenticated as the lane's account. + * + *

Only created when a deployment configured more than one account. Its whole behaviour is a + * lookup: the accounts were decided at composition, and a lane cannot change the account it runs as + * after the connection exists. + */ +final class AccountRoutingRuntimeClient implements RedisRuntimeClient { + + private final Map byAccount; + + AccountRoutingRuntimeClient(Map byAccount) { + this.byAccount = new LinkedHashMap<>(byAccount); + } + + @Override + public RedisDeploymentMode mode() { + return byAccount.get(RedisAccount.APPLICATION).mode(); + } + + @Override + public RedisLaneConnection openLane(RedisLane lane, Optional routingKey) { + return delegate(lane).openLane(lane, routingKey); + } + + private RedisRuntimeClient delegate(RedisLane lane) { + RedisRuntimeClient client = byAccount.get(lane.account()); + // Falling back to the application account is the documented behaviour of an unconfigured + // account, not a failure: a deployment with one account is the common case. + return client == null ? byAccount.get(RedisAccount.APPLICATION) : client; + } + + @Override + public void close() { + // Distinct instances only, and the application client last: it is the one every unconfigured + // account fell back to, so closing it first would tear out lanes still being drained. + Set remaining = new LinkedHashSet<>(byAccount.values()); + RedisRuntimeClient application = byAccount.get(RedisAccount.APPLICATION); + remaining.remove(application); + RuntimeException first = null; + for (RedisRuntimeClient client : remaining) { + try { + client.close(); + } catch (RuntimeException failure) { + first = first == null ? failure : first; + } + } + try { + application.close(); + } catch (RuntimeException failure) { + first = first == null ? failure : first; + } + if (first != null) { + throw first; + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ClusterRuntimeClient.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ClusterRuntimeClient.java new file mode 100644 index 00000000..a1d040c2 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ClusterRuntimeClient.java @@ -0,0 +1,84 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.cluster.RedisClusterClient; +import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; +import io.lettuce.core.cluster.models.partitions.RedisClusterNode; +import io.lettuce.core.codec.ByteArrayCodec; +import java.nio.charset.StandardCharsets; +import java.util.Optional; + +/** Cluster: lanes route by slot, a lane pinned to its key's owner runs on that node alone. */ +final class ClusterRuntimeClient implements RedisRuntimeClient { + + private static final RedisSlotCalculator SLOTS = new RedisSlotCalculator(); + + private final RedisClusterClient client; + private final SharedClientResources resources; + private final ShutdownBudget shutdown; + + ClusterRuntimeClient( + RedisClusterClient client, SharedClientResources resources, ShutdownBudget shutdown) { + this.client = client; + this.resources = resources; + this.shutdown = shutdown; + } + + @Override + public RedisDeploymentMode mode() { + return RedisDeploymentMode.CLUSTER; + } + + @Override + public RedisLaneConnection openLane(RedisLane lane, Optional routingKey) { + StatefulRedisClusterConnection connection = + client.connect(ByteArrayCodec.INSTANCE); + if (!lane.pinnedToKeyOwner()) { + return new LaneConnection( + connection, RedisDriverConnection.slotRouting(connection.async()), connection::isOpen); + } + try { + // A Cluster transaction runs on one node. The slot-routing connection cannot own the window + // — its queued commands would be spread across nodes — so the lane is pinned to the node + // that owns the routing key's slot, and every key in the window is proved to share that slot + // before anything is queued. + byte[] key = + routingKey.orElseThrow( + () -> + new IllegalStateException( + "a Cluster lane pinned to its key's owner needs a routing key: the window" + + " runs on one node, and which node that is can only be decided from a" + + " key or an explicit slot tag.")); + int slot = SLOTS.applyAsInt(new String(key, StandardCharsets.UTF_8)); + RedisClusterNode owner = client.getPartitions().getMasterBySlot(slot); + if (owner == null) { + throw new IllegalStateException( + "no Cluster node currently owns slot " + + slot + + "; the topology is incomplete and a transaction opened against it would run" + + " somewhere the keys do not live"); + } + StatefulRedisConnection node = connection.getConnection(owner.getNodeId()); + // The parent is closed on release; closing it releases the node connection with it. + return new LaneConnection( + connection, RedisDriverConnection.singleNode(node.async()), node::isOpen); + } catch (RuntimeException failure) { + connection.close(); + throw failure; + } + } + + @Override + public void close() { + try { + client.shutdown( + shutdown.quietPeriod().toMillis(), shutdown.timeout().toMillis(), MILLISECONDS); + } finally { + resources.release(shutdown); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/LaneConnection.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/LaneConnection.java new file mode 100644 index 00000000..222cd76b --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/LaneConnection.java @@ -0,0 +1,37 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.LettuceSemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import java.util.function.BooleanSupplier; + +/** + * One open connection: what closes it, what runs over it, and how to ask whether it still works. + * + * @param connection what {@link #close()} closes — on a pinned Cluster lane the parent connection, + * which releases the node connection with it + * @param driver the driver surface commands are sent on + * @param openCheck whether the driver still reports the connection open + */ +record LaneConnection( + AutoCloseable connection, RedisDriverConnection driver, BooleanSupplier openCheck) + implements RedisRuntimeClient.RedisLaneConnection { + + @Override + public SemanticRedisCommands commands() { + return new LettuceSemanticRedisCommands(driver.commands()); + } + + @Override + public boolean open() { + return openCheck.getAsBoolean(); + } + + @Override + public void close() { + try { + connection.close(); + } catch (Exception failure) { + throw new IllegalStateException("a Redis lane connection could not be closed", failure); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisAccount.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisAccount.java new file mode 100644 index 00000000..ba6c05e8 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisAccount.java @@ -0,0 +1,46 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * The Redis account a connection authenticates as. + * + *

Redis ACLs authenticate a named user, and the privileges that user carries are the only + * privileges the connection has for its whole life. So "which account" is a property of the + * connection, not of the command: a client authenticated as one account cannot run some commands as + * a less privileged one. A deployment that grants its application account {@code EVALSHA} so that + * the rate limiter works has granted it to every code path that can reach a regular connection; + * separate accounts keep the scripting grant on the connections that run scripts. + * + *

The runtime names the two accounts its own lanes use. A module that composes further lanes on + * top of the runtime — the typed SDK's admin plane — names its own account and contributes it + * through {@code RedisAccountContribution}; the runtime does not need to know it exists. An account + * with no configured credential is served by the application client, which collapses to the + * single-account deployment most services start from. + * + * @param name a short lowercase identifier, used in logs + */ +public record RedisAccount(String name) { + + // First: the constants below are built by the constructor that reads it. + private static final Pattern NAME = Pattern.compile("[a-z][a-z0-9-]{0,31}"); + + /** Ordinary data commands. The one account every deployment configures. */ + public static final RedisAccount APPLICATION = new RedisAccount("application"); + + /** Registered-script execution: {@code SCRIPT LOAD} and {@code EVALSHA}. */ + public static final RedisAccount ADVANCED = new RedisAccount("advanced"); + + public RedisAccount { + Objects.requireNonNull(name, "account name must be non-null"); + if (!NAME.matcher(name).matches()) { + throw new IllegalArgumentException("account name must be a short lowercase identifier"); + } + } + + @Override + public String toString() { + return name; + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisConnectionKind.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisConnectionKind.java new file mode 100644 index 00000000..847f1164 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisConnectionKind.java @@ -0,0 +1,29 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +/** + * The runtime's own lanes: the ones its semantic consumers and its health contributor use. + * + *

Two, because the runtime's consumers need two account/behaviour combinations: ordinary + * commands on the application account, and registered scripts on the advanced account. Blocking, + * transaction and admin lanes belong to the typed SDK, which contributes them itself. + */ +public enum RedisConnectionKind implements RedisLane { + /** Ordinary non-blocking commands on a shared, thread-safe connection. */ + REGULAR(RedisAccount.APPLICATION.name()), + /** + * Registered-script execution, which needs the scripting grants ordinary traffic must not have. + */ + SCRIPT(RedisAccount.ADVANCED.name()); + + // The name rather than the record: an enum constant's state must be deeply immutable. + private final String account; + + RedisConnectionKind(String account) { + this.account = account; + } + + @Override + public RedisAccount account() { + return new RedisAccount(account); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisDriverConnection.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisDriverConnection.java new file mode 100644 index 00000000..c037f8ed --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisDriverConnection.java @@ -0,0 +1,49 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands; +import java.util.Objects; +import java.util.Optional; + +/** + * The driver surface of one borrowed connection, for a module that speaks more of Redis than the + * runtime's semantic commands. + * + *

The typed SDK builds its own gateway over this. The runtime does not carry the SDK's command + * surface; it carries the connection, and the SDK brings the commands. + * + * @param commands the asynchronous commands every data command lives on: standalone, or + * slot-routing on Cluster + * @param transactional the same connection's single-node surface, which is the only one that can + * own a {@code MULTI}/{@code EXEC} window; empty on a slot-routing Cluster connection + */ +public record RedisDriverConnection( + RedisClusterAsyncCommands commands, + Optional> transactional) { + + public RedisDriverConnection { + Objects.requireNonNull(commands, "commands must be non-null"); + Objects.requireNonNull(transactional, "transactional must be non-null"); + } + + /** + * A single-node connection, which can own a transaction window. + * + * @param commands the node's asynchronous commands + * @return the driver connection + */ + public static RedisDriverConnection singleNode(RedisAsyncCommands commands) { + return new RedisDriverConnection(commands, Optional.of(commands)); + } + + /** + * A slot-routing Cluster connection, which cannot own a transaction window. + * + * @param commands the slot-routing asynchronous commands + * @return the driver connection + */ + public static RedisDriverConnection slotRouting( + RedisClusterAsyncCommands commands) { + return new RedisDriverConnection(commands, Optional.empty()); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLane.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLane.java new file mode 100644 index 00000000..dcc332b9 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLane.java @@ -0,0 +1,45 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +/** + * A bounded pool of connections that share an account and a connection behaviour. + * + *

Lanes exist because their failure modes are incompatible. A script needs grants ordinary + * traffic must not have; a blocking command holds its connection for the whole block; a transaction + * owns its connection between {@code MULTI} and {@code EXEC}. Sharing one pool turns any of these + * into a stall of everything else. + * + *

The runtime defines the lanes its own consumers use ({@link RedisConnectionKind}). A module + * that needs another — the typed SDK's blocking, transaction and admin lanes — implements this + * interface and contributes a limit for it; the runtime pools and drains it like its own. + * Implementations must be singletons with value identity (an enum constant), because the lane is + * the pool's key. + */ +public interface RedisLane { + + /** + * Returns the lane's name, for logs and refusals. + * + * @return the name + */ + String name(); + + /** + * Returns the account this lane's connections authenticate as. + * + * @return the account + */ + RedisAccount account(); + + /** + * Reports whether a connection must be pinned to the node that owns the caller's routing key. + * + *

Only meaningful on Cluster, where a transaction runs entirely on one node: the slot-routing + * connection every other lane uses cannot own the window. Topologies with a single owner ignore + * it. + * + * @return {@code true} when a connection is opened against the routing key's owning node + */ + default boolean pinnedToKeyOwner() { + return false; + } +} 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 new file mode 100644 index 00000000..d3951860 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLaneUnavailableException.java @@ -0,0 +1,38 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +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. + * + *

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 + * adapter reports to its own callers. + */ +public final class RedisLaneUnavailableException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private final String lane; + + /** + * Creates the failure. + * + * @param lane the lane that could not lend a connection + * @param reason a fixed, payload-free reason + */ + public RedisLaneUnavailableException(String lane, String reason) { + super(Objects.requireNonNull(reason, "reason must be non-null")); + this.lane = Objects.requireNonNull(lane, "lane must be non-null"); + } + + /** + * Returns the lane that refused. + * + * @return the lane name + */ + public String lane() { + return lane; + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisLease.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLease.java similarity index 51% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisLease.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLease.java index 850e71b4..4813ae0b 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisLease.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisLease.java @@ -1,13 +1,9 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; /** - * A borrowed connection, typed by what the caller actually needs. - * - *

The predecessor handed out {@code Object} and left the caller to cast. That is not only - * awkward — it meant the type system could not tell a caller holding a live connection from one - * holding a returned lease, and returning was a counter decrement that never closed anything. + * A borrowed connection. * *

Two things a caller must know how to do. Returning is mandatory, which is why this is {@link * AutoCloseable} and every lane is bounded. Invalidating is for the case a pooled connection cannot @@ -21,21 +17,29 @@ public interface RedisLease extends AutoCloseable { * * @return the lane */ - RedisConnectionKind kind(); + RedisLane lane(); /** - * Returns the gateway bound to this connection. + * Returns the runtime's semantic commands over this connection. * - * @return the driver seam + * @return the commands * @throws IllegalStateException when the lease has already been returned */ - RedisCommandGateway gateway(); + SemanticRedisCommands commands(); + + /** + * Returns the driver surface of this connection, for a module that brings its own commands. + * + * @return the driver connection + * @throws IllegalStateException when the lease has already been returned + */ + RedisDriverConnection driver(); /** * Marks the connection unfit for reuse, so returning it closes it instead of pooling it. * - *

Call this whenever cleanup did not complete: a failed {@code DISCARD}, an abandoned - * subscription, any path that leaves connection-scoped state behind. + *

Call this whenever cleanup did not complete: a failed {@code DISCARD}, a window that may + * still be open, any path that leaves connection-scoped state behind. */ void invalidate(); diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeClient.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeClient.java new file mode 100644 index 00000000..48298e5a --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeClient.java @@ -0,0 +1,85 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import java.util.Optional; + +/** + * The driver client for one deployment, and the only thing that knows which topology it is. + * + *

Everything above this interface is topology-agnostic: a caller asks for a lane and gets a + * connection. Which client produced it — standalone, Sentinel-resolving, or slot-routing — is + * settled once, at composition, by the strategy that matched the configured mode. + * + *

Opening a lane is separate from borrowing one. This creates a connection; the owner decides + * whether the caller is allowed to hold one. + */ +public interface RedisRuntimeClient extends AutoCloseable { + + /** + * Returns the deployment mode this client was built for. + * + * @return the bound mode + */ + RedisDeploymentMode mode(); + + /** + * Opens a connection for a lane that needs no routing decision. + * + * @param lane the lane + * @return the open lane + */ + default RedisLaneConnection openLane(RedisLane lane) { + return openLane(lane, Optional.empty()); + } + + /** + * Opens a connection for a lane. + * + *

The routing key exists for a lane {@linkplain RedisLane#pinnedToKeyOwner() pinned to its + * key's owner}: on Cluster such a connection is opened against the node that owns the key rather + * than the slot-routing connection every other lane uses. Topologies with a single owner ignore + * it. + * + * @param lane the lane + * @param routingKey a key whose slot decides which node the lane is pinned to + * @return the open lane + */ + RedisLaneConnection openLane(RedisLane lane, Optional routingKey); + + /** + * Shuts the client and its event loop down, after every lane has been closed. + * + *

Shutting the client down first would abort in-flight commands the drain was waiting for. + */ + @Override + void close(); + + /** One open connection and what can be sent over it. */ + interface RedisLaneConnection extends AutoCloseable { + + /** + * Returns the runtime's semantic commands over this connection. + * + * @return the commands + */ + SemanticRedisCommands commands(); + + /** + * Returns the driver surface of this connection, for a module that brings its own commands. + * + * @return the driver connection + */ + RedisDriverConnection driver(); + + /** + * Reports whether the connection is currently usable. + * + * @return {@code true} while the driver reports it open + */ + boolean open(); + + @Override + void close(); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java similarity index 77% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java index 42010b28..7998d5c7 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwner.java @@ -1,15 +1,12 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import java.time.Duration; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -52,10 +49,10 @@ public final class RedisRuntimeOwner implements AutoCloseable { } private final RedisRuntimeClient client; - private final Map limits; - private final Map> idle; - private final Map outstanding; - private final Map permits; + private final Map limits; + private final Map> idle; + private final Map outstanding; + private final Map permits; private final Duration acquireTimeout; private final Duration drainTimeout; private final AtomicReference state = new AtomicReference<>(State.OPEN); @@ -65,13 +62,15 @@ public final class RedisRuntimeOwner implements AutoCloseable { * Creates the owner. * * @param client the topology client whose connections this owns - * @param limits per-lane maximum connections, each held by at most one lease at a time + * @param limits per-lane maximum connections, each held by at most one lease at a time. Every + * lane a caller may borrow is named here; the runtime's own {@link RedisConnectionKind} lanes + * are required, and a module that composes further lanes contributes their limits * @param acquireTimeout how long a borrow waits for a returned connection when its lane is full * @param drainTimeout how long shutdown waits for outstanding leases */ public RedisRuntimeOwner( RedisRuntimeClient client, - Map limits, + Map limits, Duration acquireTimeout, Duration drainTimeout) { this.client = Objects.requireNonNull(client, "client must be non-null"); @@ -79,21 +78,27 @@ public final class RedisRuntimeOwner implements AutoCloseable { Objects.requireNonNull(acquireTimeout, "acquire timeout must be non-null"); this.drainTimeout = Objects.requireNonNull(drainTimeout, "drain timeout must be non-null"); Objects.requireNonNull(limits, "limits must be non-null"); - Map configured = new EnumMap<>(RedisConnectionKind.class); - Map> pools = - new EnumMap<>(RedisConnectionKind.class); - Map counters = new EnumMap<>(RedisConnectionKind.class); - Map lanes = new EnumMap<>(RedisConnectionKind.class); for (RedisConnectionKind kind : RedisConnectionKind.values()) { - Integer limit = limits.get(kind); - if (limit == null || limit < 1) { + if (!limits.containsKey(kind)) { throw new IllegalArgumentException("connection lane " + kind + " needs a positive limit"); } - configured.put(kind, limit); - pools.put(kind, new ArrayDeque<>()); - counters.put(kind, 0); + } + Map configured = new LinkedHashMap<>(); + Map> pools = new LinkedHashMap<>(); + Map counters = new LinkedHashMap<>(); + Map lanes = new LinkedHashMap<>(); + for (Map.Entry entry : limits.entrySet()) { + RedisLane lane = Objects.requireNonNull(entry.getKey(), "lane must be non-null"); + Integer limit = entry.getValue(); + if (limit == null || limit < 1) { + throw new IllegalArgumentException( + "connection lane " + lane.name() + " needs a positive limit"); + } + configured.put(lane, limit); + pools.put(lane, new ArrayDeque<>()); + counters.put(lane, 0); // Fair, so a burst is served in arrival order rather than starving the earliest waiter. - lanes.put(kind, new Semaphore(limit, true)); + lanes.put(lane, new Semaphore(limit, true)); } this.limits = Map.copyOf(configured); this.idle = pools; @@ -115,10 +120,10 @@ public final class RedisRuntimeOwner implements AutoCloseable { * * @param kind the lane * @return the lease, which must be closed - * @throws RedisCommandRejectedException when the lane stayed full for the acquire timeout or the + * @throws RedisLaneUnavailableException when the lane stayed full for the acquire timeout or the * owner is closing */ - public RedisLease borrow(RedisConnectionKind kind) { + public RedisLease borrow(RedisLane kind) { return borrow(kind, Optional.empty()); } @@ -133,14 +138,21 @@ public final class RedisRuntimeOwner implements AutoCloseable { * @param kind the lane * @param routingKey a key whose slot decides the node, on topologies that have more than one * @return the lease, which must be closed - * @throws RedisCommandRejectedException when the lane stayed full for the acquire timeout or the + * @throws RedisLaneUnavailableException when the lane stayed full for the acquire timeout or the * owner is closing + * @throws IllegalArgumentException when no limit was configured for the lane */ - public RedisLease borrow(RedisConnectionKind kind, Optional routingKey) { + public RedisLease borrow(RedisLane kind, Optional routingKey) { Objects.requireNonNull(kind, "connection kind must be non-null"); Objects.requireNonNull(routingKey, "routing key must be non-null"); + if (!permits.containsKey(kind)) { + throw new IllegalArgumentException( + "connection lane " + + kind.name() + + " was never composed; the module that uses it contributes its limit"); + } if (state.get() != State.OPEN) { - throw notAccepting(); + throw notAccepting(kind); } // The limit is the lane's connection count: a lease holds one connection for one round trip, // so a burst above it waits for a returned connection instead of being refused against a @@ -153,12 +165,13 @@ public final class RedisRuntimeOwner implements AutoCloseable { admitted = lane.tryAcquire(acquireTimeout.toNanos(), TimeUnit.NANOSECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); - throw reject("interrupted while waiting for a connection on lane " + kind); + throw reject(kind, "interrupted while waiting for a connection on lane " + kind.name()); } if (!admitted) { throw reject( + kind, "connection lane " - + kind + + kind.name() + " reached its limit of " + limits.get(kind) + " and no connection was returned within " @@ -167,7 +180,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { synchronized (monitor) { if (state.get() != State.OPEN) { lane.release(); - throw notAccepting(); + throw notAccepting(kind); } outstanding.put(kind, outstanding.get(kind) + 1); } @@ -198,9 +211,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { } private void release( - RedisConnectionKind kind, - RedisRuntimeClient.RedisLaneConnection connection, - boolean reusable) { + RedisLane kind, RedisRuntimeClient.RedisLaneConnection connection, boolean reusable) { boolean drained; synchronized (monitor) { outstanding.put(kind, outstanding.get(kind) - 1); @@ -273,8 +284,9 @@ public final class RedisRuntimeOwner implements AutoCloseable { } } - private RedisCommandRejectedException notAccepting() { + private RedisLaneUnavailableException notAccepting(RedisLane lane) { return reject( + lane, "the Redis runtime is " + state.get() + " and is not accepting new work; a lease taken during shutdown would either be" @@ -283,10 +295,8 @@ public final class RedisRuntimeOwner implements AutoCloseable { // Every refusal here happens before a command exists, so it is always "not sent": a caller may // treat it as unavailable rather than as a write that might have landed. - private RedisCommandRejectedException reject(String reason) { - return new RedisCommandRejectedException( - reason, - RedisFailureMetadata.notSent("CONNECTION", CommandAccess.NONE, false, client.mode())); + private static RedisLaneUnavailableException reject(RedisLane lane, String reason) { + return new RedisLaneUnavailableException(lane.name(), reason); } /** @@ -295,7 +305,7 @@ public final class RedisRuntimeOwner implements AutoCloseable { * @param kind the lane * @return the outstanding count */ - public int outstanding(RedisConnectionKind kind) { + public int outstanding(RedisLane kind) { synchronized (monitor) { return outstanding.get(Objects.requireNonNull(kind, "connection kind must be non-null")); } @@ -313,31 +323,39 @@ public final class RedisRuntimeOwner implements AutoCloseable { /** A borrowed connection, typed, returned once, and invalidatable. */ public final class Lease implements RedisLease { - private final RedisConnectionKind kind; + private final RedisLane kind; private final RedisRuntimeClient.RedisLaneConnection connection; private boolean reusable; private boolean closed; private Lease( - RedisConnectionKind kind, - RedisRuntimeClient.RedisLaneConnection connection, - boolean reusable) { + RedisLane kind, RedisRuntimeClient.RedisLaneConnection connection, boolean reusable) { this.kind = kind; this.connection = connection; this.reusable = reusable; } @Override - public RedisConnectionKind kind() { + public RedisLane lane() { return kind; } @Override - public RedisCommandGateway gateway() { + public SemanticRedisCommands commands() { + requireOpen(); + return connection.commands(); + } + + @Override + public RedisDriverConnection driver() { + requireOpen(); + return connection.driver(); + } + + private void requireOpen() { if (closed) { throw new IllegalStateException("this Redis lease was already returned"); } - return connection.gateway(); } @Override diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisTopologyClientFactory.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisTopologyClientFactory.java similarity index 55% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisTopologyClientFactory.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisTopologyClientFactory.java index 39f0f964..5466850e 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisTopologyClientFactory.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisTopologyClientFactory.java @@ -1,13 +1,8 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.RedisSlotCalculator; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCredentialResolver.RedisCredentials; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.LettuceRedisCommandGateway; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCredentialResolver.RedisCredentials; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisCredentialsProvider; @@ -15,29 +10,20 @@ import io.lettuce.core.RedisURI; import io.lettuce.core.SocketOptions; import io.lettuce.core.SslOptions; import io.lettuce.core.TimeoutOptions; -import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; -import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; -import io.lettuce.core.cluster.models.partitions.RedisClusterNode; -import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.resource.ClientResources; import io.lettuce.core.resource.DefaultClientResources; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; -import java.util.EnumMap; -import java.util.LinkedHashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; /** * Builds the clients the configured topology and the configured accounts call for. @@ -46,7 +32,7 @@ import java.util.concurrent.atomic.AtomicInteger; * them. A deployment that declares Sentinel and gets a standalone client would work — until the * first promotion, at which point it would keep writing to a server that is no longer the primary. * So the mode picks the strategy and a mode whose prerequisites are missing fails at {@link - * RedisSdkSettings#validate()}, before this class is ever reached. + * RedisRuntimeSettings#validate()}, before this class is ever reached. * *

Orthogonally to the topology, a deployment may authenticate different lanes as different Redis * accounts. That cannot be expressed on one client: an ACL user is bound at authentication and @@ -62,11 +48,9 @@ import java.util.concurrent.atomic.AtomicInteger; */ public final class RedisTopologyClientFactory { - private static final RedisSlotCalculator SLOTS = new RedisSlotCalculator(); + private final RedisRuntimeSettings settings; - private final RedisSdkSettings settings; - - private final Map credentials; + private final Map credentials; private final Optional sentinelCredentials; @@ -98,13 +82,14 @@ public final class RedisTopologyClientFactory { * Creates the factory. * * @param settings the validated settings - * @param credentials the resolved account for each configured role + * @param credentials the resolved credentials of each configured account; the application + * account's may be absent (anonymous access), every other account named here gets a client * @param sentinelCredentials the resolved Sentinel control account, when one is configured * @param tlsMaterial opens configured TLS material */ public RedisTopologyClientFactory( - RedisSdkSettings settings, - Map credentials, + RedisRuntimeSettings settings, + Map credentials, Optional sentinelCredentials, TlsMaterialSource tlsMaterial) { this.settings = Objects.requireNonNull(settings, "settings must be non-null"); @@ -123,24 +108,24 @@ public final class RedisTopologyClientFactory { public RedisRuntimeClient create() { // One event-loop group for every account, not one per account. `ClientResources` carries // `max(2, cores)` IO threads plus a computation pool and a timer; a deployment with an - // application, an advanced and a pub/sub account used to get three of each, so an eight-core + // application, an advanced and an admin account used to get three of each, so an eight-core // pod ran twenty-four IO threads to talk to one Redis. The accounts differ in who they // authenticate as, which is a property of the connection, not of the threads that carry it. SharedClientResources shared = new SharedClientResources(resources()); - Map byRole = new EnumMap<>(RedisCredentialRole.class); + Map byAccount = new LinkedHashMap<>(); List created = new ArrayList<>(); try { RedisRuntimeClient application = - clientFor(Optional.ofNullable(credentials.get(RedisCredentialRole.APPLICATION)), shared); - byRole.put(RedisCredentialRole.APPLICATION, application); + clientFor(Optional.ofNullable(credentials.get(RedisAccount.APPLICATION)), shared); + byAccount.put(RedisAccount.APPLICATION, application); created.add(application); - for (RedisCredentialRole role : RedisCredentialRole.values()) { - if (role == RedisCredentialRole.APPLICATION || !credentials.containsKey(role)) { + for (Map.Entry account : credentials.entrySet()) { + if (account.getKey().equals(RedisAccount.APPLICATION)) { continue; } - RedisRuntimeClient client = clientFor(Optional.of(credentials.get(role)), shared); + RedisRuntimeClient client = clientFor(Optional.of(account.getValue()), shared); created.add(client); - byRole.put(role, client); + byAccount.put(account.getKey(), client); } } catch (RuntimeException failure) { // A half-built set would leak the event loops of the clients that did get created. Closing @@ -149,9 +134,9 @@ public final class RedisTopologyClientFactory { shared.shutdownAfterFailedBuild(shutdown()); throw failure; } - return byRole.size() == 1 - ? byRole.get(RedisCredentialRole.APPLICATION) - : new RoleRoutingRuntimeClient(byRole); + return byAccount.size() == 1 + ? byAccount.get(RedisAccount.APPLICATION) + : new AccountRoutingRuntimeClient(byAccount); } private static void closeQuietly(RedisRuntimeClient client) { @@ -326,7 +311,7 @@ public final class RedisTopologyClientFactory { private SslOptions sslOptions() { SslOptions.Builder ssl = SslOptions.builder().jdkSslProvider(); - RedisSdkSettings.Tls tls = settings.getTls(); + RedisRuntimeSettings.Tls tls = settings.getTls(); if (tls.getTrustMaterialResource() != null && !tls.getTrustMaterialResource().isBlank()) { ssl.trustManager(material("trust material", tls.getTrustMaterialResource())); } @@ -370,288 +355,12 @@ public final class RedisTopologyClientFactory { return () -> tlsMaterial.open(location); } - /** - * One {@link ClientResources} shared by every account, stopped by the last client to let go. - * - *

Lettuce treats whoever passes resources to {@code RedisClient.create} as their owner and - * {@code client.shutdown()} deliberately leaves them running, so somebody has to stop them. With - * one group per account that owner was obvious and wasteful; with one group for all of them the - * ownership is shared, and a hold count is the smallest thing that still guarantees the loops are - * stopped exactly once, after the last client that was using them. - */ - private static final class SharedClientResources { - - private final ClientResources resources; - private final AtomicInteger holds = new AtomicInteger(); - private final AtomicBoolean stopped = new AtomicBoolean(); - - private SharedClientResources(ClientResources resources) { - this.resources = resources; - } - - /** Takes a hold and returns the group to hand to a driver client. */ - private ClientResources acquire() { - holds.incrementAndGet(); - return resources; - } - - /** Releases one hold, stopping the loops when it was the last one. */ - private void release(ShutdownBudget shutdown) { - if (holds.decrementAndGet() == 0) { - stop(shutdown); - } - } - - /** - * Stops the loops after a build that did not finish. - * - *

Unconditional, not "when nothing holds it": a hold is taken before the driver client that - * would release it exists, so a failure between those two points leaves a hold nobody can give - * back. {@link #stop} is idempotent, so the clients that were built and closed normally having - * already stopped the group costs nothing here. - */ - private void shutdownAfterFailedBuild(ShutdownBudget shutdown) { - stop(shutdown); - } - - private void stop(ShutdownBudget shutdown) { - if (stopped.compareAndSet(false, true)) { - shutdown.await( - resources.shutdown( - shutdown.quietPeriod().toMillis(), shutdown.timeout().toMillis(), MILLISECONDS)); - } - } - } - - /** Standalone and Sentinel share a client type; only how the URI resolves differs. */ - private static final class StandaloneRuntimeClient implements RedisRuntimeClient { - - private final RedisClient client; - private final SharedClientResources resources; - private final RedisDeploymentMode mode; - - private final ShutdownBudget shutdown; - - private StandaloneRuntimeClient( - RedisClient client, - SharedClientResources resources, - ShutdownBudget shutdown, - RedisDeploymentMode mode) { - this.client = client; - this.resources = resources; - this.shutdown = shutdown; - this.mode = mode; - } - - @Override - public RedisDeploymentMode mode() { - return mode; - } - - @Override - public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { - // A single server owns every key, so a routing key carries no information here. - StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); - return new LaneConnection( - connection, new LettuceRedisCommandGateway(connection.async()), connection::isOpen); - } - - @Override - public void close() { - try { - client.shutdown( - shutdown.quietPeriod().toMillis(), shutdown.timeout().toMillis(), MILLISECONDS); - } finally { - // After the client, never before: the resources are the threads the shutdown runs on. And - // awaited, not fired — shutdown() returns a future, so ignoring it means returning while - // the event loop is still running and reporting a clean stop that has not happened. The - // group is shared across accounts, so only the last client to release actually stops it. - resources.release(shutdown); - } - } - } - - /** Cluster: data lanes route by slot, the transaction lane is pinned to the slot's owner. */ - private static final class ClusterRuntimeClient implements RedisRuntimeClient { - - private final RedisClusterClient client; - private final SharedClientResources resources; - - private final ShutdownBudget shutdown; - - private ClusterRuntimeClient( - RedisClusterClient client, SharedClientResources resources, ShutdownBudget shutdown) { - this.client = client; - this.resources = resources; - this.shutdown = shutdown; - } - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.CLUSTER; - } - - @Override - public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { - StatefulRedisClusterConnection connection = - client.connect(ByteArrayCodec.INSTANCE); - if (kind != RedisConnectionKind.TRANSACTION) { - return new LaneConnection( - connection, new LettuceRedisCommandGateway(connection.async()), connection::isOpen); - } - try { - // A Cluster transaction runs on one node. The slot-routing connection cannot own the - // window — its queued commands would be spread across nodes — so the lane is pinned to the - // node that owns the routing key's slot, and every key in the window is proved to share - // that slot before anything is queued. - byte[] key = - routingKey.orElseThrow( - () -> - new IllegalStateException( - "a Cluster transaction lane needs a routing key: the window runs on one" - + " node, and which node that is can only be decided from a key or an" - + " explicit slot tag.")); - int slot = SLOTS.applyAsInt(new String(key, StandardCharsets.UTF_8)); - RedisClusterNode owner = client.getPartitions().getMasterBySlot(slot); - if (owner == null) { - throw new IllegalStateException( - "no Cluster node currently owns slot " - + slot - + "; the topology is incomplete and a transaction opened against it would run" - + " somewhere the keys do not live"); - } - StatefulRedisConnection node = connection.getConnection(owner.getNodeId()); - // The parent is closed on release; closing it releases the node connection with it. - return new LaneConnection( - connection, new LettuceRedisCommandGateway(node.async()), node::isOpen); - } catch (RuntimeException failure) { - connection.close(); - throw failure; - } - } - - @Override - public void close() { - try { - client.shutdown( - shutdown.quietPeriod().toMillis(), shutdown.timeout().toMillis(), MILLISECONDS); - } finally { - resources.release(shutdown); - } - } - } - - /** - * Routes each lane to the client that authenticated as the lane's account. - * - *

Only created when a deployment configured more than one account. Its whole behaviour is a - * lookup: the roles were decided at composition, and a lane cannot change the account it runs as - * after the connection exists. - */ - private static final class RoleRoutingRuntimeClient implements RedisRuntimeClient { - - private final Map byRole; - - private RoleRoutingRuntimeClient(Map byRole) { - this.byRole = new EnumMap<>(byRole); - } - - @Override - public RedisDeploymentMode mode() { - return byRole.get(RedisCredentialRole.APPLICATION).mode(); - } - - @Override - public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { - return delegate(kind).openLane(kind, routingKey); - } - - private RedisRuntimeClient delegate(RedisConnectionKind kind) { - RedisRuntimeClient client = byRole.get(kind.credentialRole()); - // Falling back to the application account is the documented behaviour of an unconfigured - // role, not a failure: a deployment with one account is the common case. - return client == null ? byRole.get(RedisCredentialRole.APPLICATION) : client; - } - - @Override - public void close() { - // Distinct instances only, and the application client last: it is the one every unconfigured - // role fell back to, so closing it first would tear out lanes still being drained. - Set remaining = new LinkedHashSet<>(byRole.values()); - RedisRuntimeClient application = byRole.get(RedisCredentialRole.APPLICATION); - remaining.remove(application); - RuntimeException first = null; - for (RedisRuntimeClient client : remaining) { - try { - client.close(); - } catch (RuntimeException failure) { - first = first == null ? failure : first; - } - } - try { - application.close(); - } catch (RuntimeException failure) { - first = first == null ? failure : first; - } - if (first != null) { - throw first; - } - } - } - - private record LaneConnection( - AutoCloseable connection, - RedisCommandGateway gateway, - java.util.function.BooleanSupplier openCheck) - implements RedisRuntimeClient.RedisLaneConnection { - - @Override - public RedisCommandGateway gateway() { - return gateway; - } - - @Override - public boolean open() { - return openCheck.getAsBoolean(); - } - - @Override - public void close() { - try { - connection.close(); - } catch (Exception failure) { - throw new IllegalStateException("a Redis lane connection could not be closed", failure); - } - } - } - private ShutdownBudget shutdown() { return new ShutdownBudget( settings.getLifecycle().getShutdownQuietPeriod(), settings.getLifecycle().getShutdownTimeout()); } - /** - * How long a client is given to stop, and the wait that makes stopping observable. - * - * @param quietPeriod the window in which new work must stop arriving - * @param timeout the total budget - */ - private record ShutdownBudget(Duration quietPeriod, Duration timeout) { - - void await(java.util.concurrent.Future pending) { - try { - pending.get(timeout.toMillis() + quietPeriod.toMillis(), MILLISECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (java.util.concurrent.ExecutionException - | java.util.concurrent.TimeoutException failure) { - // Shutdown is best effort past its own budget; what it must not do is claim to be done. - LOG.warn("Redis client resources did not shut down within {}", timeout, failure); - } - } - } - private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RedisTopologyClientFactory.class); diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/SharedClientResources.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/SharedClientResources.java new file mode 100644 index 00000000..9582fae3 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/SharedClientResources.java @@ -0,0 +1,60 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import io.lettuce.core.resource.ClientResources; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * One {@link ClientResources} shared by every account, stopped by the last client to let go. + * + *

Lettuce treats whoever passes resources to {@code RedisClient.create} as their owner and + * {@code client.shutdown()} deliberately leaves them running, so somebody has to stop them. With + * one group per account that owner was obvious and wasteful; with one group for all of them the + * ownership is shared, and a hold count is the smallest thing that still guarantees the loops are + * stopped exactly once, after the last client that was using them. + */ +final class SharedClientResources { + + private final ClientResources resources; + private final AtomicInteger holds = new AtomicInteger(); + private final AtomicBoolean stopped = new AtomicBoolean(); + + SharedClientResources(ClientResources resources) { + this.resources = resources; + } + + /** Takes a hold and returns the group to hand to a driver client. */ + ClientResources acquire() { + holds.incrementAndGet(); + return resources; + } + + /** Releases one hold, stopping the loops when it was the last one. */ + void release(ShutdownBudget shutdown) { + if (holds.decrementAndGet() == 0) { + stop(shutdown); + } + } + + /** + * Stops the loops after a build that did not finish. + * + *

Unconditional, not "when nothing holds it": a hold is taken before the driver client that + * would release it exists, so a failure between those two points leaves a hold nobody can give + * back. {@link #stop} is idempotent, so the clients that were built and closed normally having + * already stopped the group costs nothing here. + */ + void shutdownAfterFailedBuild(ShutdownBudget shutdown) { + stop(shutdown); + } + + private void stop(ShutdownBudget shutdown) { + if (stopped.compareAndSet(false, true)) { + shutdown.await( + resources.shutdown( + shutdown.quietPeriod().toMillis(), shutdown.timeout().toMillis(), MILLISECONDS)); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ShutdownBudget.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ShutdownBudget.java new file mode 100644 index 00000000..550cb553 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/ShutdownBudget.java @@ -0,0 +1,32 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import java.time.Duration; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeoutException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * How long a client is given to stop, and the wait that makes stopping observable. + * + * @param quietPeriod the window in which new work must stop arriving + * @param timeout the total budget + */ +record ShutdownBudget(Duration quietPeriod, Duration timeout) { + + private static final Logger LOG = LoggerFactory.getLogger(ShutdownBudget.class); + + void await(Future pending) { + try { + pending.get(timeout.toMillis() + quietPeriod.toMillis(), MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException failure) { + // Shutdown is best effort past its own budget; what it must not do is claim to be done. + LOG.warn("Redis client resources did not shut down within {}", timeout, failure); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StandaloneRuntimeClient.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StandaloneRuntimeClient.java new file mode 100644 index 00000000..6e91fa05 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StandaloneRuntimeClient.java @@ -0,0 +1,56 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import io.lettuce.core.RedisClient; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.codec.ByteArrayCodec; +import java.util.Optional; + +/** Standalone and Sentinel share a client type; only how the URI resolves differs. */ +final class StandaloneRuntimeClient implements RedisRuntimeClient { + + private final RedisClient client; + private final SharedClientResources resources; + private final ShutdownBudget shutdown; + private final RedisDeploymentMode mode; + + StandaloneRuntimeClient( + RedisClient client, + SharedClientResources resources, + ShutdownBudget shutdown, + RedisDeploymentMode mode) { + this.client = client; + this.resources = resources; + this.shutdown = shutdown; + this.mode = mode; + } + + @Override + public RedisDeploymentMode mode() { + return mode; + } + + @Override + public RedisLaneConnection openLane(RedisLane lane, Optional routingKey) { + // A single server owns every key, so a routing key carries no information here. + StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); + return new LaneConnection( + connection, RedisDriverConnection.singleNode(connection.async()), connection::isOpen); + } + + @Override + public void close() { + try { + client.shutdown( + shutdown.quietPeriod().toMillis(), shutdown.timeout().toMillis(), MILLISECONDS); + } finally { + // After the client, never before: the resources are the threads the shutdown runs on. And + // awaited, not fired — shutdown() returns a future, so ignoring it means returning while the + // event loop is still running and reporting a clean stop that has not happened. The group is + // shared across accounts, so only the last client to release actually stops it. + resources.release(shutdown); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRules.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/key/RedisKeyRules.java similarity index 98% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRules.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/key/RedisKeyRules.java index 55a7b9d7..58a8ac66 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRules.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/key/RedisKeyRules.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.key; import java.util.Locale; import java.util.Objects; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisNamespace.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/key/RedisNamespace.java similarity index 93% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisNamespace.java rename to src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/key/RedisNamespace.java index 56c73270..bee4b837 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisNamespace.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/key/RedisNamespace.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.key; /** * Structural key prefix that isolates an environment, a service, and a domain. diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCorrectnessRoles.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCorrectnessRoles.java deleted file mode 100644 index 7b6a8b5c..00000000 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCorrectnessRoles.java +++ /dev/null @@ -1,86 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; - -import java.util.Map; -import java.util.Set; -import org.springframework.core.env.Environment; - -/** - * The roles that need Redis for correctness rather than for speed. - * - *

Session, idempotency, rate limiting and leases all produce a wrong answer when Redis is gone, - * not a slow one: a replayed payment, an unenforced quota, two holders of a lease. Serving traffic - * without them is worse than not serving it, so a deployment that selected any of them gates its - * readiness on Redis. A cache does not appear here — a cache outage is degradation, and taking the - * pod out of service during it removes capacity from a system that is already slower than usual. - * - *

This holder exists because that question is asked in two places that must never disagree: the - * condition that decides whether the {@code redisRequired} health contributor is created, and the - * environment post-processor that decides whether the readiness group may name it. When those two - * drifted apart the result was not a subtle mismatch — Boot refuses to start a health group naming - * a contributor that does not exist, so every Redis-off deployment failed at startup with - * {@code Included health contributor 'redisRequired' in group 'readiness' does not exist}. One - * constant, two readers. - */ -public final class RedisCorrectnessRoles { - - /** The bean name of the readiness-gating health contributor. */ - public static final String REQUIRED_HEALTH_CONTRIBUTOR = "redisRequired"; - - /** The bean name of the degradation-only health contributor. */ - public static final String OPTIONAL_HEALTH_CONTRIBUTOR = "redisOptional"; - - /** Role selector property to the value that selects Redis for correctness. */ - private static final Map SELECTORS = - Map.of( - "ca-skeleton.security.auth-mode", "redis-session", - "ca-skeleton.capabilities.idempotency.provider", "redis", - "ca-skeleton.capabilities.rate-limit.provider", "redis", - "ca-skeleton.capabilities.lease.provider", "redis"); - - /** - * The roles among {@link #SELECTORS} whose Redis programs run on the SCRIPT lane, which - * authenticates as the advanced account. Session is absent: it issues plain commands. - */ - private static final Set SCRIPT_SELECTORS = - Set.of( - "ca-skeleton.capabilities.idempotency.provider", - "ca-skeleton.capabilities.rate-limit.provider", - "ca-skeleton.capabilities.lease.provider"); - - private RedisCorrectnessRoles() { - throw new AssertionError("RedisCorrectnessRoles is a constant holder"); - } - - /** - * Reports whether any correctness role selected Redis. - * - * @param environment the environment to read selectors from - * @return {@code true} when at least one correctness role is bound to Redis - */ - public static boolean anySelected(Environment environment) { - return SELECTORS.entrySet().stream() - .anyMatch(role -> role.getValue().equalsIgnoreCase(environment.getProperty(role.getKey()))); - } - - /** - * Reports whether a correctness role that runs registered scripts selected Redis. - * - * @param environment the environment to read selectors from - * @return {@code true} when the SCRIPT lane carries a correctness role - */ - public static boolean anyScriptRoleSelected(Environment environment) { - return SCRIPT_SELECTORS.stream() - .anyMatch( - selector -> - SELECTORS.get(selector).equalsIgnoreCase(environment.getProperty(selector))); - } - - /** - * Returns the selector properties and the values that select Redis, for diagnostics. - * - * @return the selector map - */ - public static Map selectors() { - return SELECTORS; - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionKind.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionKind.java deleted file mode 100644 index 0def0f4a..00000000 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionKind.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisCommandDescriptor; -import java.util.Objects; - -/** - * Connection lane a command must run on. - * - *

The lanes exist because their failure modes are incompatible. A blocking command holds its - * connection for the whole block; a transaction owns its connection between {@code MULTI} and - * {@code EXEC}; a subscribed connection cannot run ordinary commands at all; and admin traffic runs - * under a different account. Sharing one pool between them turns any of these into a stall of - * everything else. - * - *

A lane also decides which account the command authenticates as — see {@link - * #credentialRole()}. That is not a second concern bolted on: the reason blocking, scripting, admin - * and subscription traffic are separated at all is that each needs a different combination of - * connection behaviour and privilege, and deriving both from one enum is what keeps a command from - * running on the right pool under the wrong account. - */ -public enum RedisConnectionKind { - /** Ordinary non-blocking commands on a shared, thread-safe connection. */ - REGULAR, - /** Blocking commands on a dedicated bounded pool. */ - BLOCKING, - /** One exclusive connection per optimistic transaction. */ - TRANSACTION, - /** - * Registered-script execution, which needs the scripting grants ordinary traffic must not have. - */ - SCRIPT, - /** Subscription lifecycle only. */ - PUBSUB, - /** Read-only diagnostics under the admin account. */ - ADMIN; - - /** - * Returns the credential role this lane authenticates as. - * - *

Least privilege only means something if the accounts differ. The application account runs - * ordinary data commands and must not be able to execute a script; the advanced account can, and - * exists so that a compromised request path cannot reach {@code EVALSHA}; admin is read-only - * diagnostics on its own connection. A deployment that configures no separate account for a role - * falls back to the application account, which is a deliberate choice it makes rather than one - * the SDK makes silently — {@code RedisSdkSettings} warns about it at startup. - * - * @return the role whose credentials this lane's connection authenticates with - */ - public RedisCredentialRole credentialRole() { - return switch (this) { - case REGULAR, BLOCKING, TRANSACTION -> RedisCredentialRole.APPLICATION; - case SCRIPT -> RedisCredentialRole.ADVANCED; - case PUBSUB -> RedisCredentialRole.PUBSUB; - case ADMIN -> RedisCredentialRole.ADMIN; - }; - } - - /** - * Selects the lane a descriptor must run on. - * - * @param descriptor the command descriptor - * @return the required lane - */ - public static RedisConnectionKind forCommand(RedisCommandDescriptor descriptor) { - Objects.requireNonNull(descriptor, "descriptor must be non-null"); - if (descriptor.blocking()) { - return BLOCKING; - } - return switch (descriptor.access()) { - case ADMIN_READONLY -> ADMIN; - case APPLICATION, APPLICATION_ADVANCED, RAW_GATEWAY, EXTENSION -> REGULAR; - case NONE -> throw new IllegalArgumentException("a blocked command has no connection lane"); - }; - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java deleted file mode 100644 index dabef402..00000000 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; - -/** - * The Redis account a connection authenticates as. - * - *

Redis 6 ACLs authenticate a named user, and the privileges that user carries are the only - * privileges the connection has for its whole life. So "which account" is a property of the - * connection, not of the command — a single client authenticated as one account cannot run some - * commands as a less privileged one. - * - *

That is why the roles here exist and why they are separate clients rather than a field on a - * request. A deployment that grants its application account {@code EVALSHA} so that the rate - * limiter works has granted it to every code path that can reach a regular connection, including - * the ones that only ever meant to read a cache entry. Splitting the roles keeps the scripting - * grant on the connections that run scripts. - * - *

A role with no configured credential reference is served by the application client. That - * collapses back to the single-account deployment most templates start from, without the SDK - * pretending an account exists that does not. - */ -public enum RedisCredentialRole { - /** Ordinary data commands. The one role every deployment configures. */ - APPLICATION, - /** Registered-script execution: {@code SCRIPT LOAD} and {@code EVALSHA} only. */ - ADVANCED, - /** Subscription traffic, whose channel patterns are granted separately from keys. */ - PUBSUB, - /** Read-only diagnostics, on its own connection so its grants never reach request paths. */ - ADMIN -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeClient.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeClient.java deleted file mode 100644 index 84a9b13c..00000000 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeClient.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; -import java.util.Optional; - -/** - * The driver client for one deployment, and the only thing that knows which topology it is. - * - *

Everything above this interface is topology-agnostic: an operation asks for a lane and gets a - * {@link RedisCommandGateway}. Which client produced it — standalone, Sentinel-resolving, or - * slot-routing — is settled once, at composition, by the strategy that matched the configured mode. - * That is what keeps "the SDK behaves the same on every topology" a property of the code rather - * than a claim in a document. - * - *

Opening a lane is separate from borrowing one. This creates a connection; the registry decides - * whether the caller is allowed to hold one. - */ -public interface RedisRuntimeClient extends AutoCloseable { - - /** - * Returns the deployment mode this client was built for. - * - * @return the bound mode - */ - RedisDeploymentMode mode(); - - /** - * Opens a connection for a lane that needs no routing decision. - * - * @param kind the lane - * @return the open lane - */ - default RedisLaneConnection openLane(RedisConnectionKind kind) { - return openLane(kind, Optional.empty()); - } - - /** - * Opens a connection for a lane and returns the gateway over it. - * - *

The routing key exists for one case, and it is not an optimisation: a Cluster transaction - * runs entirely on one node, so the lane has to be opened against the node that owns the keys - * rather than against the slot-routing connection every other lane uses. Which node that is - * cannot be known from the lane alone — only a key can say — so the caller supplies one. - * Topologies with a single owner ignore it. - * - * @param kind the lane - * @param routingKey a key whose slot decides which node the lane is pinned to, where the topology - * has more than one - * @return the open lane - */ - RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey); - - /** - * Shuts the client and its event loop down. - * - *

Called after every lane has been closed. Shutting the client down first would abort - * in-flight commands that the drain was still waiting for. - */ - @Override - void close(); - - /** One open connection and the gateway bound to it. */ - interface RedisLaneConnection extends AutoCloseable { - - /** - * Returns the gateway over this connection. - * - * @return the driver seam - */ - RedisCommandGateway gateway(); - - /** - * Reports whether the connection is currently usable. - * - * @return {@code true} while the driver reports it open - */ - boolean open(); - - @Override - void close(); - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubGateway.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubGateway.java deleted file mode 100644 index 1153c036..00000000 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubGateway.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import java.util.List; -import java.util.concurrent.CompletionStage; -import java.util.function.BiConsumer; - -/** - * The narrow driver surface subscriptions are written against. - * - *

A subscription is not a command with a reply: it occupies its connection for as long as it - * lives. It therefore has its own seam, bound to a connection borrowed from {@code - * RedisConnectionKind.PUBSUB}, so a long-lived listener can never sit on the lane ordinary commands - * share. - */ -public interface RedisPubSubGateway { - - /** - * Publishes to a channel. - * - * @param channel the rendered channel - * @param message the encoded message - * @return how many subscribers received it - */ - CompletionStage publish(byte[] channel, byte[] message); - - /** - * Publishes to a shard channel. - * - * @param channel the rendered channel - * @param message the encoded message - * @return how many subscribers received it - */ - CompletionStage publishSharded(byte[] channel, byte[] message); - - /** - * Starts a subscription. - * - * @param targets the rendered channels or patterns - * @param kind whether the targets are channels, patterns, or shard channels - * @param listener receives the rendered channel and the raw message - * @return a handle that stops the subscription - */ - RedisSubscriptionHandle subscribe( - List targets, SubscriptionKind kind, BiConsumer listener); - - /** What a set of subscription targets means. */ - enum SubscriptionKind { - /** Exact channel names. */ - CHANNEL, - - /** Glob patterns, which are R2 because their fan-out is unbounded. */ - PATTERN, - - /** Shard channels, available from Redis 7.0. */ - SHARD - } - - /** A live subscription. */ - interface RedisSubscriptionHandle extends AutoCloseable { - - /** - * Reports whether the subscription is still delivering. - * - * @return {@code true} until it is closed - */ - boolean active(); - - @Override - void close(); - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/redis-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 223a63b5..8d33591a 100644 --- a/src/adapter/outbound/redis-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/adapter/outbound/redis-runtime/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1 +1 @@ -dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration +dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisRuntimePackageBoundaryTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisRuntimePackageBoundaryTest.java new file mode 100644 index 00000000..cca306a9 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisRuntimePackageBoundaryTest.java @@ -0,0 +1,70 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** + * The runtime knows nothing of the typed SDK built on it. + * + *

The runtime once lived in the SDK's own package ({@code ...cache.redis.sdk}), carried the + * SDK's command catalogue types, its 118-method gateway and its admin lane, and named its settings + * after the SDK. A consumer that needed a cache read compiled against all of it. These checks keep + * the split from growing back: no runtime source may sit in or import the SDK's package, and no + * runtime type may carry the SDK's name. + */ +class RedisRuntimePackageBoundaryTest { + + private static final Path RUNTIME_ROOT = Path.of("src"); + + private static final String SDK_PACKAGE = "dev.caskeleton.adapter.outbound.cache.redis.sdk"; + + @Test + void noRuntimeSourceReferencesTheTypedSdkPackage() { + List offenders = + javaSources().stream() + .filter(source -> read(source).contains(SDK_PACKAGE)) + .map(Path::toString) + .toList(); + + assertThat(offenders).isEmpty(); + } + + @Test + void noRuntimeTypeIsNamedAfterTheSdk() { + List offenders = + javaSources().stream() + .map(source -> source.getFileName().toString()) + .filter(name -> name.contains("Sdk")) + .toList(); + + assertThat(offenders).isEmpty(); + } + + private static List javaSources() { + try (Stream paths = Files.walk(RUNTIME_ROOT)) { + return paths + .filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".java")) + .filter(path -> !path.endsWith("RedisRuntimePackageBoundaryTest.java")) + .sorted() + .toList(); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + + private static String read(Path source) { + try { + return Files.readString(source); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/LiveRedisCompositionTest.java similarity index 89% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/LiveRedisCompositionTest.java index 7588357f..06bdddae 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/LiveRedisCompositionTest.java @@ -1,12 +1,12 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import java.time.Duration; import java.util.Optional; import java.util.concurrent.TimeUnit; @@ -47,9 +47,9 @@ class LiveRedisCompositionTest { private ApplicationContextRunner runner(String password, String advancedPassword) { ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)) .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, // The fixture account's real password. It used to be `nopass`, so this could have // been any string at all and the lane would still have connected — which is why // there was nothing to distinguish a working credential from a wrong one. @@ -68,7 +68,7 @@ class LiveRedisCompositionTest { "app.redis.namespace.service=order", "app.redis.namespace.domain=shared"); return endpoint.mode() - == dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode.SENTINEL + == dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode.SENTINEL ? runner.withPropertyValues("app.redis.sentinel.master-name=" + endpoint.requireMasterId()) : runner; } @@ -87,7 +87,7 @@ class LiveRedisCompositionTest { org.assertj.core.api.Assertions.assertThatThrownBy( () -> { try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - lease.gateway().ping().toCompletableFuture().get(5, TimeUnit.SECONDS); + lease.commands().ping().toCompletableFuture().get(5, TimeUnit.SECONDS); } }) .as("authentication is actually enforced by the fixture") @@ -121,7 +121,7 @@ class LiveRedisCompositionTest { try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { String reply = - lease.gateway().ping().toCompletableFuture().get(5, TimeUnit.SECONDS); + lease.commands().ping().toCompletableFuture().get(5, TimeUnit.SECONDS); assertThat(reply).isEqualTo("PONG"); } assertThat(owner.outstanding(RedisConnectionKind.REGULAR)) @@ -152,7 +152,7 @@ class LiveRedisCompositionTest { "app.redis.authentication.advanced-credential-reference=secret://" + "ca-skeleton-application-advanced@environment/" + ADVANCED_PASSWORD_NAME, - "ca-skeleton.capabilities.idempotency.provider=redis"); + "test.redis.correctness=script"); } @Test diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/LiveRedisTlsTest.java similarity index 86% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/LiveRedisTlsTest.java index da591766..d2e72fbd 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/LiveRedisTlsTest.java @@ -1,11 +1,11 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLease; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; @@ -41,9 +41,9 @@ class LiveRedisTlsTest { private ApplicationContextRunner runner(String trustMaterial) { return new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)) .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> Optional.of("fixture-application")) .withPropertyValues( "app.redis.enabled=true", @@ -68,7 +68,7 @@ class LiveRedisTlsTest { assertThat(context).hasNotFailed(); try (RedisLease lease = context.getBean(RedisRuntimeOwner.class).borrow(RedisConnectionKind.REGULAR)) { - assertThat(lease.gateway().ping().toCompletableFuture().get(5, TimeUnit.SECONDS)) + assertThat(lease.commands().ping().toCompletableFuture().get(5, TimeUnit.SECONDS)) .isEqualTo("PONG"); } }); @@ -95,7 +95,7 @@ class LiveRedisTlsTest { assertThat(context).hasNotFailed(); try (RedisLease lease = context.getBean(RedisRuntimeOwner.class).borrow(RedisConnectionKind.REGULAR)) { - assertThat(lease.gateway().ping().toCompletableFuture().get(5, TimeUnit.SECONDS)) + assertThat(lease.commands().ping().toCompletableFuture().get(5, TimeUnit.SECONDS)) .isEqualTo("PONG"); } }); @@ -120,9 +120,9 @@ class LiveRedisTlsTest { // The lane's server has no plaintext port at all, so this is the assertion that the previous // test proved something: if the client were quietly speaking plaintext, this would pass too. new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)) .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> Optional.of("fixture-application")) .withPropertyValues( "app.redis.enabled=true", diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/PropertyCorrectnessRequirement.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/PropertyCorrectnessRequirement.java new file mode 100644 index 00000000..346f5cd2 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/PropertyCorrectnessRequirement.java @@ -0,0 +1,26 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import org.springframework.core.env.Environment; + +/** + * Stands in, in this leaf's tests, for the module that owns the correctness roles. + * + *

The runtime does not know which roles need Redis; {@code cache-redis} answers that in + * production. Here a test says it directly: {@code test.redis.correctness=required} for a role that + * issues plain commands, {@code script} for one that runs registered programs. + */ +public final class PropertyCorrectnessRequirement implements RedisCorrectnessRequirement { + + static final String PROPERTY = "test.redis.correctness"; + + @Override + public boolean required(Environment environment) { + String value = environment.getProperty(PROPERTY, ""); + return "required".equals(value) || "script".equals(value); + } + + @Override + public boolean requiresScriptLane(Environment environment) { + return "script".equals(environment.getProperty(PROPERTY, "")); + } +} diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisHealthContributorTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java similarity index 64% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisHealthContributorTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java index 9d22deb4..5c656746 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisHealthContributorTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisHealthContributorTest.java @@ -1,16 +1,17 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +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.RedisRuntimeClient; +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.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -21,7 +22,7 @@ class RedisHealthContributorTest { /** One connection per lane and almost no patience, so holding a lease saturates that lane. */ private static RedisRuntimeOwner narrowOwner(RedisRuntimeClient client) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 1); } @@ -65,47 +66,22 @@ class RedisHealthContributorTest { .containsExactly(false, "unreachable"); } - private static RedisRuntimeClient client(RedisCommandGateway gateway) { - return client(gateway, gateway); + private static RedisRuntimeClient client(SemanticRedisCommands commands) { + return StubRedisRuntimeClient.serving(commands); } private static RedisRuntimeClient client( - RedisCommandGateway regular, RedisCommandGateway script) { - return new RedisRuntimeClient() { - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return kind == RedisConnectionKind.SCRIPT ? script : regular; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - }; + SemanticRedisCommands regular, SemanticRedisCommands script) { + return StubRedisRuntimeClient.servingPerLane( + lane -> lane == RedisConnectionKind.SCRIPT ? script : regular); } /** A gateway whose account is refused the script path, as Redis refuses it. */ - private static RedisCommandGateway refusingScripts() { - return (RedisCommandGateway) + private static SemanticRedisCommands refusingScripts() { + return (SemanticRedisCommands) Proxy.newProxyInstance( - RedisCommandGateway.class.getClassLoader(), - new Class[] {RedisCommandGateway.class}, + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, (proxy, method, arguments) -> switch (method.getName()) { case "loadScript" -> @@ -119,11 +95,11 @@ class RedisHealthContributorTest { } /** A gateway that answers PING. */ - private static RedisCommandGateway answering() { - return (RedisCommandGateway) + private static SemanticRedisCommands answering() { + return (SemanticRedisCommands) Proxy.newProxyInstance( - RedisCommandGateway.class.getClassLoader(), - new Class[] {RedisCommandGateway.class}, + SemanticRedisCommands.class.getClassLoader(), + new Class[] {SemanticRedisCommands.class}, (proxy, method, arguments) -> switch (method.getName()) { case "ping" -> CompletableFuture.completedFuture("PONG"); diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationRegistrationTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationRegistrationTest.java similarity index 92% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationRegistrationTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationRegistrationTest.java index 84a3fd07..c36becdb 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationRegistrationTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationRegistrationTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; @@ -27,14 +27,15 @@ import org.springframework.core.annotation.AnnotatedElementUtils; * carries {@code @AutoConfiguration}. A rename, a move or a deleted line fails here rather than in * a deployment that starts and quietly does less than it says. */ -class RedisSdkAutoConfigurationRegistrationTest { +class RedisRuntimeAutoConfigurationRegistrationTest { private static final String IMPORTS_RESOURCE = "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports"; /** The auto-configurations this leaf publishes. */ private static final List PUBLISHED_ROOTS = - List.of("dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration"); + List.of( + "dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeAutoConfiguration"); @Test @DisplayName("the shipped registration file names every root this leaf publishes") @@ -52,7 +53,7 @@ class RedisSdkAutoConfigurationRegistrationTest { try { registered = Class.forName( - name, false, RedisSdkAutoConfigurationRegistrationTest.class.getClassLoader()); + name, false, RedisRuntimeAutoConfigurationRegistrationTest.class.getClassLoader()); } catch (ClassNotFoundException missing) { throw new AssertionError( IMPORTS_RESOURCE + " registers " + name + ", which does not exist", missing); diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java similarity index 71% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java index 0d23c412..4437818e 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeAutoConfigurationTest.java @@ -1,10 +1,12 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -14,20 +16,20 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; * Redis optionality, from both ends. * *

Off has to mean off: no settings bean, so nothing binds, nothing validates, and no Redis - * resource is opened. The previous arrangement registered {@link RedisSdkSettings} from the + * resource is opened. The previous arrangement registered {@link RedisRuntimeSettings} from the * application-wide {@code @ConfigurationPropertiesScan}, which meant a deployment with no Redis at * all still carried Redis configuration — and a deployment with malformed Redis configuration still * bound it. * - *

On has to mean validated: {@link RedisSdkSettings#validate()} had no production caller, so the - * fail-fast the class documents did not exist. A setting that disables a guardrail must stop the - * context here, before anything reaches the network. + *

On has to mean validated: {@link RedisRuntimeSettings#validate()} had no production caller, so + * the fail-fast the class documents did not exist. A setting that disables a guardrail must stop + * the context here, before anything reaches the network. */ -class RedisSdkAutoConfigurationTest { +class RedisRuntimeAutoConfigurationTest { private final ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)); /** * The runner for cases that need an enabled context to get past authentication. @@ -43,7 +45,7 @@ class RedisSdkAutoConfigurationTest { "app.redis.authentication.credential-reference=" + "secret://ca-skeleton-application@environment/APP_REDIS_PASSWORD") .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> java.util.Optional.of("resolved-" + name)); @Test @@ -52,7 +54,7 @@ class RedisSdkAutoConfigurationTest { runner.run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(RedisSdkSettings.class); + assertThat(context).doesNotHaveBean(RedisRuntimeSettings.class); }); } @@ -64,7 +66,7 @@ class RedisSdkAutoConfigurationTest { .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(RedisSdkSettings.class); + assertThat(context).doesNotHaveBean(RedisRuntimeSettings.class); }); } @@ -79,11 +81,11 @@ class RedisSdkAutoConfigurationTest { "app.redis.database=7", "app.redis.nodes=", "app.redis.timeout.fast=0s", - "app.redis.blocking.max-connections=0") + "app.redis.capacity.maximum-script-connections=0") .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(RedisSdkSettings.class); + assertThat(context).doesNotHaveBean(RedisRuntimeSettings.class); }); } @@ -104,10 +106,9 @@ class RedisSdkAutoConfigurationTest { "app.redis.mode=cluster", "app.redis.nodes=node-a:7000,node-b:7001", "app.redis.authentication.credential-reference=secret://environment/APP_REDIS_PASSWORD", - "app.redis.admin.enabled=true", - "app.redis.admin.credential-reference=secret://environment/APP_REDIS_ADMIN") + "app.redis.authentication.advanced-credential-reference=secret://environment/APP_REDIS_ADV") .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> { secretLookups.incrementAndGet(); @@ -116,7 +117,7 @@ class RedisSdkAutoConfigurationTest { .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(RedisSdkSettings.class); + assertThat(context).doesNotHaveBean(RedisRuntimeSettings.class); assertThat(context).doesNotHaveBean(RedisRuntimeClient.class); assertThat(context).doesNotHaveBean(RedisRuntimeOwner.class); assertThat(secretLookups) @@ -135,12 +136,12 @@ class RedisSdkAutoConfigurationTest { "app.redis.enabled=true", "app.redis.nodes=redis-a:6379", "app.redis.authentication.credential-reference=secret://environment/APP_REDIS_PASSWORD", - // The admin plane is off, so its credential must not be resolved even though one is - // configured: resolving credentials for roles nobody selected is how an unused secret - // becomes a startup dependency. - "app.redis.admin.credential-reference=secret://environment/APP_REDIS_ADMIN") + // A sentinel credential outside Sentinel mode must not be resolved: resolving + // credentials for accounts nobody uses is how an unused secret becomes a startup + // dependency. + "app.redis.sentinel.credential-reference=secret://environment/APP_REDIS_SENTINEL") .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> { requested.add(name); @@ -167,8 +168,8 @@ class RedisSdkAutoConfigurationTest { .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(RedisSdkSettings.class); - RedisSdkSettings settings = context.getBean(RedisSdkSettings.class); + assertThat(context).hasSingleBean(RedisRuntimeSettings.class); + RedisRuntimeSettings settings = context.getBean(RedisRuntimeSettings.class); assertThat(settings.isEnabled()).isTrue(); assertThat(settings.getNodes()).containsExactly("redis-a:6379"); assertThat(context).hasSingleBean(RedisRuntimeClient.class); @@ -254,7 +255,8 @@ class RedisSdkAutoConfigurationTest { assertThat(context).hasNotFailed(); assertThat( context - .getBean(RedisSdkAutoConfiguration.RedisSdkSettingsValidation.class) + .getBean( + RedisRuntimeAutoConfiguration.RedisRuntimeSettingsValidation.class) .warnings()) .as("allowed, but the deployment is told what it chose") .anySatisfy(warning -> assertThat(warning).contains("without credentials")); @@ -270,10 +272,16 @@ class RedisSdkAutoConfigurationTest { "app.redis.enabled=true", "app.redis.nodes=redis-a:6379", "app.redis.authentication.credential-reference=secret://app@environment/APP_PW", - "app.redis.authentication.advanced-credential-reference=secret://adv@environment/ADV_PW", - "app.redis.authentication.pubsub-credential-reference=secret://ps@environment/PS_PW") + "app.redis.authentication.advanced-credential-reference=secret://adv@environment/ADV_PW") + // A module composing lanes on the runtime names its own account, as the typed SDK's admin + // plane does. The runtime resolves it like its own. .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisAccountContribution.class, + () -> + new RedisAccountContribution( + new RedisAccount("admin"), "secret://adm@environment/ADM_PW")) + .withBean( + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> { requested.add(name); @@ -283,18 +291,13 @@ class RedisSdkAutoConfigurationTest { context -> { assertThat(context).hasNotFailed(); // Named accounts that were never resolved are privilege separation on paper only. - assertThat(requested).containsExactly("APP_PW", "ADV_PW", "PS_PW"); + assertThat(requested).containsExactly("APP_PW", "ADV_PW", "ADM_PW"); assertThat( context - .getBean(RedisSdkAutoConfiguration.RedisResolvedCredentials.class) + .getBean(RedisRuntimeAutoConfiguration.RedisResolvedCredentials.class) .accounts()) .containsOnlyKeys( - dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection - .RedisCredentialRole.APPLICATION, - dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection - .RedisCredentialRole.ADVANCED, - dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection - .RedisCredentialRole.PUBSUB); + RedisAccount.APPLICATION, RedisAccount.ADVANCED, new RedisAccount("admin")); }); } @@ -306,7 +309,7 @@ class RedisSdkAutoConfigurationTest { "app.redis.enabled=true", "app.redis.authentication.credential-reference=secret://environment/ABSENT") .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> java.util.Optional.empty()) .run( context -> { @@ -367,15 +370,66 @@ class RedisSdkAutoConfigurationTest { } @Test - @DisplayName("the switch on fails the context when the admin plane has no credential of its own") - void enabledRejectsAnAdminPlaneWithoutItsOwnCredential() { - runner - .withPropertyValues("app.redis.enabled=true", "app.redis.admin.enabled=true") + @DisplayName("정합성 역할을 소유한 모듈이 required라고 답하면 redisRequired가 생긴다") + void aModuleThatNeedsRedisForCorrectnessGetsTheRequiredContributor() { + authenticated + .withPropertyValues("app.redis.enabled=true", "test.redis.correctness=required") + .run(context -> assertThat(context).hasBean("redisRequired")); + } + + @Test + @DisplayName("정합성 역할 선택이 없으면 runtime은 selector를 모르므로 redisRequired를 만들지 않는다") + void withoutARequirementTheRuntimeCreatesNoRequiredContributor() { + authenticated + // A selector the runtime used to hard-code. It means nothing to the runtime now: only the + // module that owns the role can say it needs Redis. + .withPropertyValues( + "app.redis.enabled=true", "ca-skeleton.capabilities.idempotency.provider=redis") + .run(context -> assertThat(context).doesNotHaveBean("redisRequired")); + } + + @Test + void aLaneAnotherModuleContributesIsPooledByTheOwner() { + authenticated + .withPropertyValues("app.redis.enabled=true") + .withBean( + RedisLaneContribution.class, + () -> new RedisLaneContribution(ContributedLane.EXCLUSIVE, 3)) .run( context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasStackTraceContaining("app.redis.admin.credential-reference"); + // when + RedisRuntimeOwner owner = context.getBean(RedisRuntimeOwner.class); + + // then + assertThat(owner.outstanding(ContributedLane.EXCLUSIVE)).isZero(); }); } + + @Test + void aLaneComposedTwiceFailsTheContext() { + authenticated + .withPropertyValues("app.redis.enabled=true") + .withBean( + "first", + RedisLaneContribution.class, + () -> new RedisLaneContribution(ContributedLane.EXCLUSIVE, 1)) + .withBean( + "second", + RedisLaneContribution.class, + () -> new RedisLaneContribution(ContributedLane.EXCLUSIVE, 2)) + .run( + context -> + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("Redis lane EXCLUSIVE was composed twice")); + } + + /** A lane another module composes on the runtime, the way the typed SDK does. */ + private enum ContributedLane implements RedisLane { + EXCLUSIVE; + + @Override + public RedisAccount account() { + return RedisAccount.APPLICATION; + } + } } diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeSettingsTest.java similarity index 78% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeSettingsTest.java index 0a0babb0..dade54b4 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisRuntimeSettingsTest.java @@ -1,18 +1,18 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import java.time.Duration; import org.junit.jupiter.api.Test; -class RedisSdkSettingsTest { +class RedisRuntimeSettingsTest { @Test void clusterRejectsDatabaseOtherThanZero() { - RedisSdkSettings properties = validProperties(); + RedisRuntimeSettings properties = validProperties(); properties.setMode(RedisDeploymentMode.CLUSTER); properties.setDatabase(1); @@ -22,7 +22,7 @@ class RedisSdkSettingsTest { @Test void standaloneAcceptsANonZeroDatabase() { - RedisSdkSettings properties = validProperties(); + RedisRuntimeSettings properties = validProperties(); properties.setMode(RedisDeploymentMode.STANDALONE); properties.setDatabase(3); @@ -31,7 +31,7 @@ class RedisSdkSettingsTest { @Test void namespaceTokensAreValidatedAtStartup() { - RedisSdkSettings properties = validProperties(); + RedisRuntimeSettings properties = validProperties(); properties.getNamespace().setService("Order Service"); assertThatThrownBy(properties::validate) @@ -41,33 +41,24 @@ class RedisSdkSettingsTest { @Test void aFastTimeoutAboveTheGuardrailWarnsAndFarAboveItFails() { - RedisSdkSettings warning = validProperties(); + RedisRuntimeSettings warning = validProperties(); warning.getTimeout().setFast(Duration.ofSeconds(6)); assertThat(warning.validate()).anySatisfy(line -> assertThat(line).contains("fast timeout")); - RedisSdkSettings failure = validProperties(); + RedisRuntimeSettings failure = validProperties(); failure.getTimeout().setFast(Duration.ofSeconds(31)); assertThatThrownBy(failure::validate).hasMessageContaining("must not exceed 30s"); } - @Test - void theAdminPlaneRequiresItsOwnCredential() { - RedisSdkSettings properties = validProperties(); - properties.getAdmin().setEnabled(true); - - assertThatThrownBy(properties::validate) - .hasMessageContaining("app.redis.admin.credential-reference"); - } - @Test void aClientCertificateWithoutItsKeyIsRefusedAtStartup() { // The registry declares this one as a relationship between two settings rather than a switch, // so RequiredWhenIsEnforcedTest skips it and this is where the claim is kept. Before it was // checked here, the missing key surfaced as a NullPointerException while the SSL options were // being built — at the first connection, not at startup. - RedisSdkSettings properties = validProperties(); + RedisRuntimeSettings properties = validProperties(); properties.getTls().setEnabled(true); properties.getTls().setClientCertificateResource("classpath:redis/client.crt"); @@ -84,7 +75,7 @@ class RedisSdkSettingsTest { // What the registry used to claim was required whenever TLS was on. A server certificate from // a public CA verifies against the JDK trust anchors, and a server that does not ask for a // client certificate is not given one, so neither setting is a startup requirement. - RedisSdkSettings properties = validProperties(); + RedisRuntimeSettings properties = validProperties(); properties.getTls().setEnabled(true); assertThatCode(properties::validate).doesNotThrowAnyException(); @@ -92,7 +83,7 @@ class RedisSdkSettingsTest { @Test void defaultsMatchTheDesignGuardrails() { - RedisSdkSettings properties = new RedisSdkSettings(); + RedisRuntimeSettings properties = new RedisRuntimeSettings(); assertThat(properties.isEnabled()).isFalse(); assertThat(properties.getMode()).isEqualTo(RedisDeploymentMode.STANDALONE); @@ -100,13 +91,10 @@ class RedisSdkSettingsTest { assertThat(properties.getTimeout().getFast()).isEqualTo(Duration.ofMillis(500)); assertThat(properties.getTimeout().getScript()).isEqualTo(Duration.ofSeconds(1)); assertThat(properties.getTimeout().getBatch()).isEqualTo(Duration.ofSeconds(2)); - assertThat(properties.getBlocking().getMaxConnections()).isEqualTo(32); - assertThat(properties.getTransaction().getMaxConnections()).isEqualTo(16); - assertThat(properties.getAdmin().isEnabled()).isFalse(); } - private static RedisSdkSettings validProperties() { - RedisSdkSettings properties = new RedisSdkSettings(); + private static RedisRuntimeSettings validProperties() { + RedisRuntimeSettings properties = new RedisRuntimeSettings(); properties.setEnabled(true); properties.getNamespace().setEnvironment("prod"); properties.getNamespace().setService("order"); @@ -121,7 +109,7 @@ class RedisSdkSettingsTest { @Test void authenticationIsRequiredUnlessAnonymousIsDeclared() { - RedisSdkSettings missing = validProperties(); + RedisRuntimeSettings missing = validProperties(); missing.getAuthentication().setCredentialReference(null); // Booting anonymously is not a lenient default: on a deployment that switched the `default` @@ -131,7 +119,7 @@ class RedisSdkSettingsTest { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no application credential reference"); - RedisSdkSettings declared = validProperties(); + RedisRuntimeSettings declared = validProperties(); declared.getAuthentication().setCredentialReference(""); declared.getAuthentication().setAnonymousAccessAccepted(true); @@ -142,12 +130,12 @@ class RedisSdkSettingsTest { @Test void aSingleAccountDeploymentIsToldThatScriptingRunsAsTheApplicationAccount() { - RedisSdkSettings properties = validProperties(); + RedisRuntimeSettings properties = validProperties(); assertThat(properties.validate()) .anySatisfy(line -> assertThat(line).contains("no advanced credential reference")); - RedisSdkSettings separated = validProperties(); + RedisRuntimeSettings separated = validProperties(); separated .getAuthentication() .setAdvancedCredentialReference("secret://ca-skeleton-advanced@environment/APP_REDIS_ADV"); diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneAdmissionTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java similarity index 69% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneAdmissionTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java index 464cc7de..bbed4f58 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneAdmissionTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneAdmissionTest.java @@ -1,22 +1,19 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.InstanceOfAssertFactories.type; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +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.cache.redis.runtime.connection.StubRedisRuntimeClient; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Optional; import java.util.Queue; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.ConcurrentLinkedQueue; @@ -24,6 +21,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.StaticListableBeanFactory; /** * The SCRIPT lane limit is a connection bound, not a concurrency cap on callers. @@ -74,20 +72,24 @@ class RedisScriptLaneAdmissionTest { // then assertThat(refused) - .asInstanceOf(type(RedisCommandRejectedException.class)) - .extracting(Throwable::getMessage, rejection -> rejection.metadata().ambiguousExecution()) + .asInstanceOf(type(RedisLaneUnavailableException.class)) + .extracting(Throwable::getMessage, RedisLaneUnavailableException::lane) .containsExactly( "connection lane SCRIPT reached its limit of 1 and no connection was returned" - + " within PT0.05S [command=CONNECTION, mode=STANDALONE, ambiguous=false]", - false); + + " within PT0.05S", + "SCRIPT"); } } private static RedisRuntimeOwner owner(int scriptConnections, Duration acquireTimeout) { - RedisSdkSettings settings = new RedisSdkSettings(); + RedisRuntimeSettings settings = new RedisRuntimeSettings(); settings.getCapacity().setMaximumScriptConnections(scriptConnections); settings.getLifecycle().setAcquireTimeout(acquireTimeout); - return new RedisSdkAutoConfiguration().redisRuntimeOwner(new NoopClient(), settings); + return new RedisRuntimeAutoConfiguration() + .redisRuntimeOwner( + StubRedisRuntimeClient.serving(null), + settings, + new StaticListableBeanFactory().getBeanProvider(RedisLaneContribution.class)); } /** One semantic script call: the lease is held until the test lets the script complete. */ @@ -99,7 +101,7 @@ class RedisScriptLaneAdmissionTest { scriptsComplete.await(); return SERVED; } - } catch (RedisCommandRejectedException refused) { + } catch (RedisLaneUnavailableException refused) { return refused.getMessage(); } catch (InterruptedException | BrokenBarrierException interrupted) { Thread.currentThread().interrupt(); @@ -125,33 +127,4 @@ class RedisScriptLaneAdmissionTest { Thread.onSpinWait(); } } - - private static final class NoopClient implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return null; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } } diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java new file mode 100644 index 00000000..6d8c40bf --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RedisScriptLaneCapacityTest.java @@ -0,0 +1,42 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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.cache.redis.runtime.connection.StubRedisRuntimeClient; +import java.time.Duration; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.StaticListableBeanFactory; + +class RedisScriptLaneCapacityTest { + + @Test + void scriptPhysicalConnectionsAreBoundedSeparatelyFromCommandCapacity() { + RedisRuntimeSettings settings = new RedisRuntimeSettings(); + settings.getCapacity().setMaximumInFlightCommands(64); + settings.getCapacity().setMaximumScriptConnections(2); + settings.getLifecycle().setAcquireTimeout(Duration.ofMillis(50)); + + RedisRuntimeOwner owner = + new RedisRuntimeAutoConfiguration() + .redisRuntimeOwner( + StubRedisRuntimeClient.serving(null), + settings, + new StaticListableBeanFactory().getBeanProvider(RedisLaneContribution.class)); + + RedisLease first = owner.borrow(RedisConnectionKind.SCRIPT); + RedisLease second = owner.borrow(RedisConnectionKind.SCRIPT); + try { + assertThatThrownBy(() -> owner.borrow(RedisConnectionKind.SCRIPT)) + .isInstanceOf(RedisLaneUnavailableException.class) + .hasMessageContaining("limit of 2"); + } finally { + first.close(); + second.close(); + owner.close(); + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RequiredWhenIsEnforcedTest.java similarity index 93% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RequiredWhenIsEnforcedTest.java index 65ca0cce..13e80a77 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/config/RequiredWhenIsEnforcedTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.config; import static org.assertj.core.api.Assertions.assertThat; @@ -32,7 +32,7 @@ import org.yaml.snakeyaml.Yaml; *

Each machine-readable condition — {@code =} — becomes a case: enable the * condition, omit the property, and require the context to fail. Prose conditions ("… is * configured") are deliberately excluded and are exactly the rows whose rule is a relationship - * between two settings rather than a switch; {@code RedisSdkSettingsTest} covers those. + * between two settings rather than a switch; {@code RedisRuntimeSettingsTest} covers those. * *

A row that cannot pass this test has two honest fixes and one dishonest one. Enforce the * requirement, or weaken the declaration to what is true. Deleting the case is the third. @@ -98,9 +98,9 @@ class RequiredWhenIsEnforcedTest { properties.removeIf(entry -> entry.startsWith(property + "=")); new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(RedisRuntimeAutoConfiguration.class)) .withBean( - RedisSdkAutoConfiguration.RedisSecretSource.class, + RedisRuntimeAutoConfiguration.RedisSecretSource.class, () -> name -> Optional.of("resolved-" + name)) .withPropertyValues(properties.toArray(String[]::new)) .run( @@ -126,9 +126,6 @@ class RequiredWhenIsEnforcedTest { extra.put( "app.redis.sentinel.credential-reference", "secret://s@environment/APP_REDIS_SENTINEL"); } - if ("app.redis.admin.enabled".equals(condition.property())) { - extra.put("app.redis.admin.credential-reference", "secret://a@environment/APP_REDIS_ADMIN"); - } return extra; } diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java similarity index 73% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java index 054301ec..78569797 100644 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/RedisRuntimeOwnerTest.java @@ -1,14 +1,14 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; 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.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; import java.time.Duration; import java.util.ArrayList; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -27,11 +27,22 @@ import org.junit.jupiter.api.Test; */ class RedisRuntimeOwnerTest { - private static Map limits(int perLane) { - Map limits = new EnumMap<>(RedisConnectionKind.class); + /** A lane another module composes on the runtime, the way the typed SDK does. */ + private enum ContributedLane implements RedisLane { + EXCLUSIVE; + + @Override + public RedisAccount account() { + return RedisAccount.APPLICATION; + } + } + + private static Map limits(int perLane) { + Map limits = new LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, perLane); } + limits.put(ContributedLane.EXCLUSIVE, perLane); return limits; } @@ -67,7 +78,7 @@ class RedisRuntimeOwnerTest { RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR); lease.close(); - assertThatThrownBy(lease::gateway) + assertThatThrownBy(lease::commands) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("already returned"); } @@ -77,14 +88,14 @@ class RedisRuntimeOwnerTest { @DisplayName("an invalidated connection is closed rather than pooled") void anInvalidatedConnectionIsNotReused() { try (RedisRuntimeOwner owner = owner(2, Duration.ofSeconds(1))) { - RedisLease lease = owner.borrow(RedisConnectionKind.TRANSACTION); + RedisLease lease = owner.borrow(ContributedLane.EXCLUSIVE); // The transaction case: DISCARD did not land, so the window may still be open. Pooling this // connection would queue the next borrower's command into somebody else's transaction. lease.invalidate(); lease.close(); assertThat(client.closed).isEqualTo(1); - owner.borrow(RedisConnectionKind.TRANSACTION).close(); + owner.borrow(ContributedLane.EXCLUSIVE).close(); assertThat(client.opened).as("a fresh connection, not the poisoned one").isEqualTo(2); } } @@ -93,10 +104,10 @@ class RedisRuntimeOwnerTest { @DisplayName("a lane still at its ceiling when the acquire wait runs out refuses") void anExhaustedLaneRefusesOnceTheAcquireWaitRunsOut() { try (RedisRuntimeOwner owner = owner(1, Duration.ofSeconds(1))) { - RedisLease held = owner.borrow(RedisConnectionKind.BLOCKING); + RedisLease held = owner.borrow(ContributedLane.EXCLUSIVE); - assertThatThrownBy(() -> owner.borrow(RedisConnectionKind.BLOCKING)) - .isInstanceOf(RedisCommandRejectedException.class) + assertThatThrownBy(() -> owner.borrow(ContributedLane.EXCLUSIVE)) + .isInstanceOf(RedisLaneUnavailableException.class) .hasMessageContaining("reached its limit"); held.close(); @@ -121,7 +132,7 @@ class RedisRuntimeOwnerTest { assertThat(owner.state()).isEqualTo(RedisRuntimeOwner.State.DRAINING); try { owner.borrow(RedisConnectionKind.REGULAR); - } catch (RedisCommandRejectedException expected) { + } catch (RedisLaneUnavailableException expected) { refused.set(true); } draining.countDown(); @@ -138,7 +149,7 @@ class RedisRuntimeOwnerTest { void theClientShutsDownLast() { RedisRuntimeOwner owner = owner(2, Duration.ofSeconds(1)); owner.borrow(RedisConnectionKind.REGULAR).close(); - owner.borrow(RedisConnectionKind.ADMIN).close(); + owner.borrow(RedisConnectionKind.SCRIPT).close(); owner.close(); @@ -174,6 +185,50 @@ class RedisRuntimeOwnerTest { } } + @Test + void aLaneNobodyComposedIsRefusedByName() { + try (RedisRuntimeOwner owner = owner(1, Duration.ofSeconds(1))) { + RedisLane unknown = + new RedisLane() { + @Override + public String name() { + return "UNCOMPOSED"; + } + + @Override + public RedisAccount account() { + return RedisAccount.APPLICATION; + } + }; + + // when + Throwable refused = catchThrowable(() -> owner.borrow(unknown)); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UNCOMPOSED was never composed"); + } + } + + @Test + void anOwnerWithoutTheRuntimesOwnLanesCannotBeBuilt() { + // given + Map contributedOnly = Map.of(ContributedLane.EXCLUSIVE, 1); + + // when + Throwable refused = + catchThrowable( + () -> + new RedisRuntimeOwner( + client, contributedOnly, Duration.ofMillis(50), Duration.ofSeconds(1))); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("REGULAR needs a positive limit"); + } + /** A driver stand-in that records the order of what it was asked to do. */ private static final class FakeClient implements RedisRuntimeClient { @@ -193,8 +248,7 @@ class RedisRuntimeOwnerTest { } @Override - public RedisLaneConnection openLane( - RedisConnectionKind kind, java.util.Optional routingKey) { + public RedisLaneConnection openLane(RedisLane kind, java.util.Optional routingKey) { opened++; FakeConnection connection = new FakeConnection(this); live.add(connection); @@ -219,7 +273,12 @@ class RedisRuntimeOwnerTest { } @Override - public RedisCommandGateway gateway() { + public SemanticRedisCommands commands() { + return null; + } + + @Override + public RedisDriverConnection driver() { return null; } diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java deleted file mode 100644 index 5f4f7cf9..00000000 --- a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; -import java.time.Duration; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class RedisScriptLaneCapacityTest { - - @Test - void scriptPhysicalConnectionsAreBoundedSeparatelyFromCommandCapacity() { - RedisSdkSettings settings = new RedisSdkSettings(); - settings.getCapacity().setMaximumInFlightCommands(64); - settings.getCapacity().setMaximumScriptConnections(2); - settings.getLifecycle().setAcquireTimeout(Duration.ofMillis(50)); - - RedisRuntimeOwner owner = - new RedisSdkAutoConfiguration().redisRuntimeOwner(new NoopClient(), settings); - - RedisLease first = owner.borrow(RedisConnectionKind.SCRIPT); - RedisLease second = owner.borrow(RedisConnectionKind.SCRIPT); - try { - assertThatThrownBy(() -> owner.borrow(RedisConnectionKind.SCRIPT)) - .isInstanceOf(RedisCommandRejectedException.class) - .hasMessageContaining("limit of 2"); - } finally { - first.close(); - second.close(); - owner.close(); - } - } - - private static final class NoopClient implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { - return new RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return null; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } -} diff --git a/src/adapter/outbound/redis-runtime/src/test/resources/META-INF/spring.factories b/src/adapter/outbound/redis-runtime/src/test/resources/META-INF/spring.factories new file mode 100644 index 00000000..4fd6443c --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +# Tests stand in for the module that owns the correctness roles (cache-redis in production). +dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCorrectnessRequirement=\ +dev.caskeleton.adapter.outbound.cache.redis.runtime.config.PropertyCorrectnessRequirement diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java similarity index 98% rename from src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java rename to src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java index 1a04d383..00307b0f 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java @@ -1,6 +1,5 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk; +package dev.caskeleton.adapter.outbound.cache.redis.runtime; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import io.lettuce.core.RedisURI; import java.util.Locale; import java.util.Objects; 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 new file mode 100644 index 00000000..666de82a --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -0,0 +1,572 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.command; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.atomic.AtomicLong; + +/** + * A deterministic in-memory stand-in for the Redis server, behind {@link SemanticRedisCommands}. + * + *

The one fake of the runtime's command seam, owned by the leaf that owns the seam. It is not a + * Redis emulator. It stores strings and hashes with explicit expiry, and it applies the documented + * effect of each registered program the semantic adapters load — recognised by a marker unique to + * the program's source, and refused when unrecognised, because a fixture that quietly evaluates the + * wrong program makes the test prove nothing. The Lua itself is proven against a real server by + * {@code LiveRedisSemanticPortsTest}. + * + *

Time is explicit: {@link #advance(Duration)} is the only way the clock moves, so a TTL + * assertion is never a race. + */ +public final class InMemorySemanticRedisCommands implements SemanticRedisCommands { + + private final Map entries = new TreeMap<>(); + + private final Map> hashes = new TreeMap<>(); + + private final Map scriptSources = new HashMap<>(); + + private final AtomicLong clockMillis = new AtomicLong(System.currentTimeMillis()); + + private final AtomicLong scriptCounter = new AtomicLong(); + + /** + * Advances the fixture's clock. + * + * @param duration how far forward + */ + public void advance(Duration duration) { + clockMillis.addAndGet(duration.toMillis()); + } + + private long now() { + return clockMillis.get(); + } + + @Override + public CompletionStage get(byte[] key) { + Entry entry = live(text(key)); + return done(entry == null ? null : entry.value.clone()); + } + + @Override + public CompletionStage set( + byte[] key, byte[] value, WritePresence presence, Duration ttl) { + String rendered = text(key); + Entry existing = live(rendered); + if (presence == WritePresence.IF_ABSENT && existing != null) { + return done(false); + } + if (presence == WritePresence.IF_PRESENT && existing == null) { + return done(false); + } + entries.put(rendered, new Entry(value.clone(), now() + ttl.toMillis())); + return done(true); + } + + @Override + public CompletionStage getAndDelete(byte[] key) { + String rendered = text(key); + Entry existing = live(rendered); + entries.remove(rendered); + return done(existing == null ? null : existing.value.clone()); + } + + @Override + public CompletionStage incrementBy(byte[] key, long delta) { + String rendered = text(key); + Entry existing = live(rendered); + long current = existing == null ? 0L : Long.parseLong(existing.text()); + long updated = current + delta; + entries.put( + rendered, + new Entry( + Long.toString(updated).getBytes(StandardCharsets.UTF_8), + existing == null ? null : existing.expiresAtMillis)); + return done(updated); + } + + @Override + public CompletionStage ping() { + return done("PONG"); + } + + @Override + public CompletionStage loadScript(byte[] source) { + String digest = "script-" + scriptCounter.incrementAndGet(); + scriptSources.put(digest, new String(source, StandardCharsets.UTF_8)); + return done(digest); + } + + /** + * Applies the documented effect of the three registered rate-limit programs. + * + *

The fixture does not interpret Lua, so it recognises which program a digest was loaded from + * and applies that program's contract against its own state. Recognition is by a marker unique to + * each source: if a program is edited so its marker no longer matches, this refuses rather than + * silently applying the wrong algorithm — a fixture that quietly evaluates a fixed window when + * the code under test asked for a token bucket would make the test prove nothing. + */ + @Override + public CompletionStage> evaluateRegisteredForList( + String digest, byte[] key, List arguments) { + String source = scriptSources.get(digest); + if (source == null) { + return CompletableFuture.failedFuture( + new io.lettuce.core.RedisNoScriptException("NOSCRIPT No matching script")); + } + String rendered = text(key); + // The numeric conversion is per-branch, not up front: a lease program's first argument is an + // ownership string, and parsing it as a number turned every lease call into a failure that + // surfaced as "indeterminate" — the one outcome that looks like a legitimate answer. + // Recognition is by a marker unique to each program, and the order is deliberate: the + // idempotency release also deletes its key, so checking the lease release first would run the + // wrong emulation against it. A fixture that quietly evaluates the wrong program is worse than + // one that refuses. + if (source.contains("'tokens'")) { + return done(tokenBucket(rendered, numbers(arguments))); + } + if (source.contains("previous * weight")) { + return done(slidingCounter(rendered, numbers(arguments))); + } + if (source.contains("local windowStart = nowMillis - (nowMillis % windowMillis)")) { + return done(fixedWindow(rendered, numbers(arguments))); + } + if (source.contains("'ACQUIRED'")) { + return done(idempotencyClaim(rendered, arguments)); + } + if (source.contains("'state', ARGV[5], 'rev', rev + 1")) { + return done(idempotencyTransition(rendered, arguments)); + } + if (source.contains("if state ~= 'CLAIMED' then")) { + return done(idempotencyRelease(rendered, arguments)); + } + if (source.contains("mine .. '|'")) { + return done(idempotencyInspect(rendered, arguments)); + } + if (source.contains("redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])")) { + return done(leaseAcquire(rendered, arguments)); + } + if (source.contains("redis.call('PEXPIRE', KEYS[1], ARGV[2])") + && source.contains("existing ~= ARGV[1]")) { + return done(leaseRenew(rendered, arguments)); + } + if (source.contains("redis.call('DEL', KEYS[1])")) { + return done(leaseRelease(rendered, arguments)); + } + if (source.contains("return {1, redis.call('PTTL', KEYS[1]), existing}")) { + return done(leaseInspect(rendered, arguments)); + } + return CompletableFuture.failedFuture( + new IllegalStateException( + "the fixture does not recognise this registered program; add its effect rather than" + + " letting it evaluate as another algorithm")); + } + + private String field(String rendered, String name) { + HashEntry entry = hash(rendered).get(name); + return entry == null ? null : text(entry.value); + } + + private void setField(String rendered, String name, String value) { + hash(rendered).put(name, new HashEntry(utf8(value), null)); + } + + private List idempotencyClaim(String rendered, List arguments) { + String ownerToken = text(arguments.get(0)); + String operationId = text(arguments.get(1)); + String fingerprint = text(arguments.get(2)); + long nowMillis = now(); + long leaseTtl = Long.parseLong(text(arguments.get(5))); + String state = field(rendered, "state"); + if (state == null) { + setField(rendered, "state", "CLAIMED"); + setField(rendered, "owner", ownerToken); + setField(rendered, "attempt", "1"); + setField(rendered, "rev", "1"); + setField(rendered, "op", operationId); + setField(rendered, "fp", fingerprint); + setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); + return reply("ACQUIRED", 1, 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); + } + if (!fingerprint.equals(field(rendered, "fp"))) { + return reply("FINGERPRINT_MISMATCH", 0, 0, "", "", ""); + } + long attempt = Long.parseLong(field(rendered, "attempt")); + long rev = Long.parseLong(field(rendered, "rev")); + String owner = field(rendered, "owner"); + String op = field(rendered, "op"); + if ("COMPLETED".equals(state)) { + return reply( + "COMPLETED_REPLAY", + attempt, + rev, + owner, + field(rendered, "resp") == null ? "" : field(rendered, "resp"), + "60000"); + } + if ("ABANDONED".equals(state)) { + return reply("RECOVERY_REQUIRED", attempt, rev, owner, "", ""); + } + if (ownerToken.equals(owner)) { + return operationId.equals(op) + ? reply("REPLAYED_ACQUIRE", attempt, rev, owner, "", field(rendered, "leaseUntil")) + : reply("OWNER_OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } + long leaseUntil = Long.parseLong(field(rendered, "leaseUntil")); + if ("FAILED_RETRYABLE".equals(state) || leaseUntil <= nowMillis) { + setField(rendered, "state", "CLAIMED"); + setField(rendered, "owner", ownerToken); + setField(rendered, "attempt", Long.toString(attempt + 1)); + setField(rendered, "rev", Long.toString(rev + 1)); + setField(rendered, "op", operationId); + setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); + return reply( + "TAKEN_OVER", attempt + 1, rev + 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); + } + return reply("IN_PROGRESS", attempt, rev, owner, "", Long.toString(leaseUntil - nowMillis)); + } + + private List idempotencyTransition(String rendered, List arguments) { + String ownerToken = text(arguments.get(0)); + long expectedRev = Long.parseLong(text(arguments.get(1))); + String operationId = text(arguments.get(2)); + String fromState = text(arguments.get(3)); + String toState = text(arguments.get(4)); + String payload = text(arguments.get(5)); + String leaseUntil = text(arguments.get(6)); + String state = field(rendered, "state"); + if (state == null) { + return reply("ABSENT", 0, 0, "", "", ""); + } + long attempt = Long.parseLong(field(rendered, "attempt")); + long rev = Long.parseLong(field(rendered, "rev")); + String owner = field(rendered, "owner"); + String op = field(rendered, "op"); + if (!ownerToken.equals(owner)) { + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } + if (!operationId.equals(op)) { + return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } + // ALREADY before the revision check, matching the program: a lost reply leaves the caller + // holding the pre-transition revision. + if (state.equals(toState)) { + String stored = field(rendered, "resp"); + return reply("ALREADY", attempt, rev, owner, stored == null ? "" : stored, ""); + } + if (rev != expectedRev) { + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } + if (!state.equals(fromState)) { + return reply("WRONG_STATE", attempt, rev, owner, state, ""); + } + setField(rendered, "state", toState); + setField(rendered, "rev", Long.toString(rev + 1)); + if (!payload.isEmpty()) { + setField(rendered, "resp", payload); + } + if (!leaseUntil.isEmpty()) { + setField(rendered, "leaseUntil", Long.toString(now() + Long.parseLong(leaseUntil))); + } + return reply("APPLIED", attempt, rev + 1, owner, "", ""); + } + + private List idempotencyRelease(String rendered, List arguments) { + String ownerToken = text(arguments.get(0)); + String operationId = text(arguments.get(2)); + String state = field(rendered, "state"); + if (state == null) { + return reply("ABSENT", 0, 0, "", "", ""); + } + long attempt = Long.parseLong(field(rendered, "attempt")); + long rev = Long.parseLong(field(rendered, "rev")); + String owner = field(rendered, "owner"); + if (!ownerToken.equals(owner)) { + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } + if (!operationId.equals(field(rendered, "op"))) { + return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } + if (!"CLAIMED".equals(state)) { + return reply("WRONG_STATE", attempt, rev, owner, state, ""); + } + hashes.remove(rendered); + return reply("APPLIED", attempt, rev, owner, "", ""); + } + + private List idempotencyInspect(String rendered, List arguments) { + String ownerToken = text(arguments.get(0)); + String fingerprint = text(arguments.get(1)); + String operationId = text(arguments.get(2)); + String state = field(rendered, "state"); + if (state == null) { + return reply("ABSENT", 0, 0, "", "", ""); + } + if (!fingerprint.equals(field(rendered, "fp"))) { + return reply("FINGERPRINT_MISMATCH", 0, 0, "", "", ""); + } + long attempt = Long.parseLong(field(rendered, "attempt")); + long rev = Long.parseLong(field(rendered, "rev")); + String owner = field(rendered, "owner"); + String mine = "OTHER"; + if (ownerToken.equals(owner)) { + mine = operationId.equals(field(rendered, "op")) ? "MINE" : "OPERATION_CONFLICT"; + } + String stored = field(rendered, "resp"); + return reply(state, attempt, rev, owner, stored == null ? "" : stored, mine + "|60000"); + } + + private static List reply( + String status, long attempt, long revision, String owner, String payload, String detail) { + return List.of( + utf8(status), + attempt, + revision, + utf8(owner == null ? "" : owner), + utf8(payload), + utf8(detail)); + } + + private long[] numbers(List arguments) { + return arguments.stream().mapToLong(a -> Long.parseLong(text(a))).toArray(); + } + + private List leaseAcquire(String rendered, List arguments) { + String ownership = text(arguments.get(0)); + long ttlMillis = Long.parseLong(text(arguments.get(1))); + Entry existing = live(rendered); + if (existing == null) { + entries.put(rendered, new Entry(utf8(ownership), now() + ttlMillis)); + return List.of(1L, ttlMillis, utf8("")); + } + String holder = existing.text(); + long remaining = existing.expiresAtMillis == null ? -1 : existing.expiresAtMillis - now(); + return List.of(holder.equals(ownership) ? 2L : 0L, remaining, utf8(holder)); + } + + private List leaseRenew(String rendered, List arguments) { + String ownership = text(arguments.get(0)); + long ttlMillis = Long.parseLong(text(arguments.get(1))); + Entry existing = live(rendered); + if (existing == null) { + return List.of(0L, 0L, utf8("")); + } + String holder = existing.text(); + if (!holder.equals(ownership)) { + return List.of(-1L, existing.expiresAtMillis - now(), utf8(holder)); + } + entries.put(rendered, new Entry(existing.value, now() + ttlMillis)); + return List.of(1L, ttlMillis, utf8(holder)); + } + + private List leaseRelease(String rendered, List arguments) { + String ownership = text(arguments.get(0)); + Entry existing = live(rendered); + if (existing == null) { + return List.of(0L, 0L, utf8("")); + } + String holder = existing.text(); + if (!holder.equals(ownership)) { + return List.of(-1L, existing.expiresAtMillis - now(), utf8(holder)); + } + entries.remove(rendered); + return List.of(1L, 0L, utf8(holder)); + } + + private List leaseInspect(String rendered, List arguments) { + String ownership = text(arguments.get(0)); + Entry existing = live(rendered); + if (existing == null) { + return List.of(0L, 0L, utf8("")); + } + String holder = existing.text(); + long remaining = existing.expiresAtMillis == null ? -1 : existing.expiresAtMillis - now(); + return List.of(holder.equals(ownership) ? 1L : -1L, remaining, utf8(holder)); + } + + private List fixedWindow(String rendered, long[] argv) { + long limit = argv[0]; + long windowMillis = argv[1]; + long cost = argv[2]; + long nowMillis = now(); + long windowStart = nowMillis - Math.floorMod(nowMillis, windowMillis); + long resetAfter = (windowStart + windowMillis) - nowMillis; + // The script's layout: two fields, overwritten when the window turns. + Map fields = hash(rendered); + boolean sameWindow = fields.containsKey("start") && fieldValue(fields, "start") == windowStart; + long current = sameWindow ? fieldValue(fields, "count") : 0; + if (current + cost > limit) { + return List.of(0L, limit - current, resetAfter); + } + fields.put("start", new HashEntry(utf8(Long.toString(windowStart)), null)); + fields.put("count", new HashEntry(utf8(Long.toString(current + cost)), null)); + return List.of(1L, limit - (current + cost), resetAfter); + } + + private List slidingCounter(String rendered, long[] argv) { + long limit = argv[0]; + long windowMillis = argv[1]; + long cost = argv[2]; + long nowMillis = now(); + long windowStart = nowMillis - Math.floorMod(nowMillis, windowMillis); + long elapsed = nowMillis - windowStart; + long resetAfter = windowMillis - elapsed; + // The script's layout: start/cur/prev, rotated when the window turns. + Map fields = hash(rendered); + long storedStart = fields.containsKey("start") ? fieldValue(fields, "start") : Long.MIN_VALUE; + long current = 0; + long previous = 0; + if (storedStart == windowStart) { + current = fieldValue(fields, "cur"); + previous = fieldValue(fields, "prev"); + } else if (storedStart == windowStart - windowMillis) { + previous = fieldValue(fields, "cur"); + } + double weight = (double) (windowMillis - elapsed) / windowMillis; + long estimated = current + (long) Math.floor(previous * weight); + if (estimated + cost > limit) { + return List.of(0L, Math.max(0, limit - estimated), resetAfter); + } + fields.put("start", new HashEntry(utf8(Long.toString(windowStart)), null)); + fields.put("cur", new HashEntry(utf8(Long.toString(current + cost)), null)); + fields.put("prev", new HashEntry(utf8(Long.toString(previous)), null)); + return List.of(1L, Math.max(0, limit - (estimated + cost)), resetAfter); + } + + private List tokenBucket(String rendered, long[] argv) { + long capacity = argv[0]; + long refillTokens = argv[1]; + long refillPeriodMillis = argv[2]; + long cost = argv[3]; + long nowMillis = now(); + Map fields = hash(rendered); + boolean fresh = !fields.containsKey("tokens") || !fields.containsKey("updatedAt"); + long tokens = fresh ? capacity : fieldValue(fields, "tokens"); + long updatedAt = fresh ? nowMillis : fieldValue(fields, "updatedAt"); + if (updatedAt > nowMillis) { + updatedAt = nowMillis; + } + long periods = (nowMillis - updatedAt) / refillPeriodMillis; + if (periods > 0) { + tokens = Math.min(capacity, tokens + (periods * refillTokens)); + updatedAt = updatedAt + (periods * refillPeriodMillis); + } + long resetAfter = refillPeriodMillis - Math.floorMod(nowMillis - updatedAt, refillPeriodMillis); + boolean allowed = tokens >= cost; + if (allowed) { + tokens -= cost; + } + fields.put("tokens", new HashEntry(utf8(Long.toString(tokens)), null)); + fields.put("updatedAt", new HashEntry(utf8(Long.toString(updatedAt)), null)); + return List.of(allowed ? 1L : 0L, tokens, resetAfter); + } + + private static long fieldValue(Map fields, String field) { + HashEntry entry = fields.get(field); + return entry == null ? 0L : Long.parseLong(text(entry.value).strip()); + } + + @Override + public CompletionStage evaluateRegisteredForLong( + String digest, byte[] key, List arguments) { + String source = scriptSources.get(digest); + if (source == null) { + return CompletableFuture.failedFuture( + new io.lettuce.core.RedisNoScriptException("NOSCRIPT No matching script")); + } + 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); + } + return CompletableFuture.failedFuture( + new IllegalStateException( + "the fixture does not recognise this registered program; add its effect rather than" + + " letting it evaluate as another")); + } + + 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)) { + return 0L; + } + long ttlMillis = Long.parseLong(text(arguments.get(2))); + entries.put(rendered, new Entry(arguments.get(1), now() + ttlMillis)); + return 1L; + } + + /** Returns the live fields of a hash. */ + private Map hash(String rendered) { + return hashes.computeIfAbsent(rendered, unusedKey -> new LinkedHashMap<>()); + } + + private Entry live(String rendered) { + Entry entry = entries.get(rendered); + if (entry == null) { + return null; + } + if (entry.expiresAtMillis != null && entry.expiresAtMillis <= now()) { + entries.remove(rendered); + return null; + } + return entry; + } + + private static byte[] utf8(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static String text(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + private static CompletionStage done(R value) { + return CompletableFuture.completedFuture(value); + } + + /** Snapshot of one stored key. */ + private static final class Entry { + + private final byte[] value; + + private final Long expiresAtMillis; + + private Entry(byte[] value, Long expiresAtMillis) { + this.value = value; + this.expiresAtMillis = expiresAtMillis; + } + + private String text() { + return new String(value, StandardCharsets.UTF_8); + } + } + + /** Snapshot of one hash field. */ + private static final class HashEntry { + + private final byte[] value; + + private HashEntry(byte[] value, Long unusedExpiry) { + this.value = value; + } + } +} diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StubRedisRuntimeClient.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StubRedisRuntimeClient.java new file mode 100644 index 00000000..5ccb37f4 --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/connection/StubRedisRuntimeClient.java @@ -0,0 +1,89 @@ +package dev.caskeleton.adapter.outbound.cache.redis.runtime.connection; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; + +/** + * A {@link RedisRuntimeClient} whose lanes serve given {@link SemanticRedisCommands} and nothing + * else — no socket, no event loop — so a {@link RedisRuntimeOwner} can be driven in a unit test. + * + *

The driver surface is not served: a test that needs it is a test of the typed SDK, which runs + * against its own fixture or a real server. + */ +public final class StubRedisRuntimeClient implements RedisRuntimeClient { + + private final Function commands; + private final AtomicInteger opened = new AtomicInteger(); + + private StubRedisRuntimeClient(Function commands) { + this.commands = Objects.requireNonNull(commands, "commands must be non-null"); + } + + /** + * Serves the same commands on every lane. + * + * @param commands the commands every lane's connection answers with; may be {@code null} for a + * test that never sends one + * @return the client + */ + public static StubRedisRuntimeClient serving(SemanticRedisCommands commands) { + return new StubRedisRuntimeClient(lane -> commands); + } + + /** + * Serves commands chosen per lane. + * + * @param commands the commands for a lane + * @return the client + */ + public static StubRedisRuntimeClient servingPerLane( + Function commands) { + return new StubRedisRuntimeClient(commands); + } + + /** + * Returns how many connections were opened. + * + * @return the count + */ + public int opened() { + return opened.get(); + } + + @Override + public RedisDeploymentMode mode() { + return RedisDeploymentMode.STANDALONE; + } + + @Override + public RedisLaneConnection openLane(RedisLane lane, Optional routingKey) { + opened.incrementAndGet(); + SemanticRedisCommands served = commands.apply(lane); + return new RedisLaneConnection() { + @Override + public SemanticRedisCommands commands() { + return served; + } + + @Override + public RedisDriverConnection driver() { + throw new UnsupportedOperationException("the stub client serves no driver connection"); + } + + @Override + public boolean open() { + return true; + } + + @Override + public void close() {} + }; + } + + @Override + public void close() {} +} diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java deleted file mode 100644 index ada4e6b8..00000000 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import java.time.Duration; - -/** - * Lends the in-memory server to tests outside this package. - * - *

{@link InMemoryRedisCommandGateway} is package-private on purpose: it is the SDK's own fixture - * and nothing outside the SDK should be able to construct a driver seam. But the semantic adapters - * live in sibling packages and need a deterministic server to be testable at all, and the - * alternative — a second in-memory Redis written per adapter — is how two fixtures drift until each - * proves its own adapter against a different idea of what Redis does. - * - *

So the fixture stays package-private and this is the one door out of it. - */ -public final class InMemoryGatewayAccess { - - private final InMemoryRedisCommandGateway gateway; - - private InMemoryGatewayAccess(InMemoryRedisCommandGateway gateway) { - this.gateway = gateway; - } - - /** - * Creates a fresh in-memory server. - * - * @return the access handle - */ - public static InMemoryGatewayAccess create() { - return new InMemoryGatewayAccess(new InMemoryRedisCommandGateway()); - } - - /** - * Returns the driver seam. - * - * @return the gateway - */ - public RedisCommandGateway gateway() { - return gateway; - } - - /** - * Advances the fixture's clock. - * - * @param amount how far forward - */ - public void advance(Duration amount) { - gateway.advance(amount); - } -} diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md index 1ccb848b..7a2a8f40 100644 --- a/src/adapter/outbound/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/README.md @@ -14,30 +14,44 @@ In the service's own outbound adapter leaf — never in `domain-core` or `applic ```groovy implementation project(':adapter:outbound:redis-sdk') -implementation project(':adapter:outbound:redis-runtime') // RedisRuntimeOwner, RedisSdkSettings +implementation project(':adapter:outbound:redis-runtime') // RedisRuntimeOwner, RedisLaneContribution ``` and register both edges in that leaf's `allowed_dependencies` in `src/config/architecture/modules.json` (HARD-STOP 5). Put the adapter behind an application-core port, as for any other outbound capability. -The connections come from `redis-runtime`: its `RedisSdkAutoConfiguration` exists only while -`APP_REDIS_ENABLED=true` and provides `RedisSdkSettings` and `RedisRuntimeOwner` (one bounded lane -per `RedisConnectionKind`, each authenticated as its role's account). The service's adapter -composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's tests -is a complete worked composition (catalog, permit verifier, guard, executor, operations). +The connections come from `redis-runtime` (package `...cache.redis.runtime`, which knows nothing of +this SDK): its `RedisRuntimeAutoConfiguration` exists only while `APP_REDIS_ENABLED=true` and +provides `RedisRuntimeOwner`, which pools the runtime's own lanes (`REGULAR`, `SCRIPT`). The SDK's +blocking, transaction and admin lanes (`RedisSdkLane`) and its admin account are the SDK's: the +service contributes them to the runtime as beans, one per lane it uses, through +`RedisSdkComposition` — + +```java +@Bean RedisLaneContribution redisBlockingLane() { return RedisSdkComposition.blockingLane(32); } +@Bean RedisLaneContribution redisTransactionLane() { return RedisSdkComposition.transactionLane(16); } +@Bean RedisLaneContribution redisAdminLane() { return RedisSdkComposition.adminLane(); } +@Bean RedisAccountContribution redisAdminAccount() { + return RedisSdkComposition.adminAccount("secret://ca-skeleton-admin-readonly@environment/APP_REDIS_ADMIN"); +} +``` + +— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The service's +adapter composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's +tests is a complete worked composition (catalog, permit verifier, guard, executor, operations). ## What it provides | Package (`dev.caskeleton.adapter.outbound.cache.redis.sdk.*`) | Contents | | --- | --- | | `api.key` | typed keys (`ValueKey`, `HashKey`, `ListKey`, `SetKey`, `SortedSetKey`, `StreamKey`, `BitmapKey`, `GeoKey`, `HyperLogLogKey`), `TypedRedisKeys`, `RedisKeyRenderer`, `RedisSlotTag` | -| `api.operations` / `api.reactive` | per-structure operation interfaces, synchronous and Reactor: value, hash, hash-field expiration, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream deletion, key, batch, pub/sub, sharded pub/sub | +| `api.operations` / `api.reactive` | per-structure operation interfaces, synchronous and Reactor: value, hash, hash-field expiration, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream deletion, key, batch. No pub/sub: the SDK has no subscription transport, and the catalog blocks those commands | | `api.command`, `api.codec`, `api.error` | `OperationBudget`, permits (`MultiKeyPermit`, `AdvancedOperationPermit`), `RedisPolicyAuthority`; `RedisCodec`/`RedisPayloadCodec`; the typed exception family | | `lettuce.operations` | the `Lettuce*Operations` implementations, `RedisOperationContext`, `RedisOperationLimits` | | `lettuce.command` | `RedisCommandCatalog` (loaded from `redis-sdk/redis-command-policy.yml`), `CommandPolicyGuard` (every command is admitted here before it runs), exception translation, executors | | `lettuce.codec` | UTF-8/long/double/bytes codecs, `VersionedJsonCodec`, `RedisCodecRegistry` | -| `lettuce.observability`, `lettuce.connection` | `RedisObservation` through a no-throw sink; `SentinelFailoverObserver` | +| `lettuce.observability`, `lettuce.connection` | `RedisObservation` through a no-throw sink; `SentinelFailoverObserver`; `RedisSdkLane`, `RedisSdkComposition` (the SDK's lanes and admin account, contributed to the runtime) | | `cluster` | `SameSlotValidator`, `ClusterScanCursor`, `ClusterTopologyObserver` | | `config` | `ConfiguredRedisPolicyAuthority`, `ConfiguredRedisPermitVerifier`, `RedisCapabilityProbe`, `RedisStartupProbe` | | `programmability` | `WATCH`/`MULTI`/`EXEC` transactions (never roll back), registered scripts (`EVALSHA` only), deployed functions | @@ -65,10 +79,9 @@ The SDK reads none itself. It runs on `redis-runtime`, whose rows in `APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=true`). - Per SDK surface used: `APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE` (scripts, functions; falls back to the application account with a startup warning), - `APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE` (pub/sub), `APP_REDIS_ADMIN_ENABLED` + - `APP_REDIS_ADMIN_CREDENTIAL_REFERENCE` (admin plane), lane ceilings - `APP_REDIS_BLOCKING_MAX_CONNECTIONS`, `APP_REDIS_TRANSACTION_MAX_CONNECTIONS`, - `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. + `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. The blocking, transaction and admin lane + ceilings and the admin account's credential reference are code (`RedisSdkComposition`), not + settings — like every other SDK knob. - Topology: `APP_REDIS_SENTINEL_*` when `APP_REDIS_MODE=sentinel`, `APP_REDIS_TLS_*` for TLS. ## Tests @@ -77,7 +90,8 @@ The SDK reads none itself. It runs on `redis-runtime`, whose rows in ./gradlew :adapter:outbound:redis-sdk:test --console=plain ``` -Contract tests run the operations against the in-memory gateway from +Contract tests run the operations against this leaf's own in-memory gateway +(`InMemoryRedisCommandGateway`, test sources); the topology endpoint helper comes from `testFixtures(project(':adapter:outbound:redis-runtime'))`. The real-server lane is `redisTopologyTest` (see `infra/redis-sdk/README.md`); this leaf declares `standalone`, `sentinel` and `cluster` in `build.gradle`. `tls` is qualified by `redis-runtime`. diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilities.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilities.java index cad3ac5d..d94f9109 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilities.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilities.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import java.util.Collection; import java.util.EnumSet; import java.util.Objects; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapability.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapability.java index ad748aeb..7e1100a7 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapability.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapability.java @@ -9,8 +9,6 @@ import java.util.Objects; * minimum version is a fast pre-filter and the probe is the authority. */ public enum RedisCapability { - /** Sharded Pub/Sub ({@code SPUBLISH}/{@code SSUBSCRIBE}). */ - SHARDED_PUBSUB(7, 0, false), /** Redis Functions ({@code FUNCTION LOAD}/{@code FCALL}). */ FUNCTIONS(7, 0, false), /** Hash field expiration ({@code HEXPIRE}/{@code HPERSIST}/{@code HTTL}). */ diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersion.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersion.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersion.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersion.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandAccess.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandAccess.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandAccess.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandAccess.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandId.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandId.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandId.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandId.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandSupport.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandSupport.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandSupport.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/CommandSupport.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/KeySpec.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/KeySpec.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/KeySpec.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/KeySpec.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/PersistentKeyPermit.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/PersistentKeyPermit.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/PersistentKeyPermit.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/PersistentKeyPermit.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisCommandDescriptor.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisCommandDescriptor.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisCommandDescriptor.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisCommandDescriptor.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisRiskLevel.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisRiskLevel.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisRiskLevel.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/RedisRiskLevel.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/TimeoutProfile.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/TimeoutProfile.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/TimeoutProfile.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/TimeoutProfile.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisCommandRejectedException.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisCommandRejectedException.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisCommandRejectedException.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisCommandRejectedException.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java similarity index 98% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java index a402d3b6..faaf5df3 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisFailureMetadata.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import java.time.Duration; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisOperationException.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisOperationException.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisOperationException.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/error/RedisOperationException.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/QualifiedRedisKey.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/QualifiedRedisKey.java index c572cb9c..fec517f7 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/QualifiedRedisKey.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/QualifiedRedisKey.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.util.Objects; import java.util.Optional; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyName.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyName.java index 5dfaa335..14807d55 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyName.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyName.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; + /** * Entity plus identifier part of a qualified key. * diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRenderer.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRenderer.java index f9ec9cd3..3b5ca7e7 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRenderer.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRenderer.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; import java.util.Objects; /** diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisSlotTag.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisSlotTag.java index 6203eeb2..0627b534 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisSlotTag.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisSlotTag.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; + /** * Cluster hash tag. * diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/TypedRedisKeys.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/TypedRedisKeys.java index ce887cd0..338ccf04 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/TypedRedisKeys.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/TypedRedisKeys.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import java.util.Objects; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldOverflow.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldOverflow.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldOverflow.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldOverflow.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldSubcommand.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldSubcommand.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldSubcommand.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitFieldSubcommand.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitmapOperation.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitmapOperation.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitmapOperation.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/BitmapOperation.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Distance.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Distance.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Distance.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Distance.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/DistanceUnit.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/DistanceUnit.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/DistanceUnit.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/DistanceUnit.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Expiration.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Expiration.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Expiration.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Expiration.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationCondition.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationCondition.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationCondition.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationCondition.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoPoint.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoPoint.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoPoint.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoPoint.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoSearchRequest.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoSearchRequest.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoSearchRequest.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/GeoSearchRequest.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LexRange.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LexRange.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LexRange.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LexRange.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ListSide.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ListSide.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ListSide.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ListSide.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LongRange.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LongRange.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LongRange.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/LongRange.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PageRequest.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PageRequest.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PageRequest.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PageRequest.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubChannel.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubChannel.java deleted file mode 100644 index 2ed22a8b..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubChannel.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import java.util.Objects; - -/** - * A namespaced Pub/Sub channel. - * - *

Pub/Sub is at-most-once. A subscriber that is disconnected when a message is published never - * receives it, and no reconnect recovers it. This type is deliberately separate from any durable - * messaging abstraction so the guarantee cannot be confused at a call site. - * - * @param namespace the owning namespace - * @param name the channel name - * @param messageCodec codec for published messages - * @param the message type - */ -public record PubSubChannel( - RedisNamespace namespace, RedisKeyName name, RedisCodec messageCodec) { - - public PubSubChannel { - Objects.requireNonNull(namespace, "namespace must be non-null"); - Objects.requireNonNull(name, "name must be non-null"); - Objects.requireNonNull(messageCodec, "message codec must be non-null"); - } - - /** - * Renders the physical channel name. - * - * @return the rendered channel - */ - public String render() { - return namespace.prefix() + ':' + name.entity() + ':' + name.identifier(); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubPattern.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubPattern.java deleted file mode 100644 index d590fe3e..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/PubSubPattern.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import java.util.Objects; - -/** - * A pattern subscription confined to one namespace. - * - *

The namespace prefix is always literal; only the suffix is a glob. That keeps a pattern - * subscription from silently reaching another service's channels. - * - * @param namespace the owning namespace - * @param suffixPattern the glob applied inside the namespace - * @param messageCodec codec for published messages - * @param the message type - */ -public record PubSubPattern( - RedisNamespace namespace, String suffixPattern, RedisCodec messageCodec) { - - public PubSubPattern { - Objects.requireNonNull(namespace, "namespace must be non-null"); - Objects.requireNonNull(suffixPattern, "suffix pattern must be non-null"); - Objects.requireNonNull(messageCodec, "message codec must be non-null"); - if (suffixPattern.isBlank() || suffixPattern.indexOf(':') >= 0) { - throw new IllegalArgumentException( - "a pattern suffix must be non-blank and must not cross a namespace separator"); - } - RedisKeyRules.requireRenderedSize( - namespace.prefix() + ':' + suffixPattern, RedisKeyRules.MAX_KEY_BYTES); - } - - /** - * Renders the physical subscription pattern. - * - * @return the rendered pattern - */ - public String render() { - return namespace.prefix() + ':' + suffixPattern; - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisPubSubOperations.java deleted file mode 100644 index 2c4129a6..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisPubSubOperations.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -import java.util.Collection; - -/** - * Pub/Sub operations. - * - *

Delivery is at-most-once. Messages published while a subscriber is disconnected are lost, and - * reconnecting does not replay them. Do not build order, payment, or retry workflows on this; use a - * stream with a consumer group. - */ -public interface RedisPubSubOperations { - - /** - * Publishes a message. - * - * @param channel the channel - * @param message the message - * @param the message type - * @return the number of clients that received the message - */ - long publish(PubSubChannel channel, V message); - - /** - * Subscribes to channels. - * - * @param channels the channels - * @param handler the message callback - * @param the message type - * @return the subscription handle - */ - Subscription subscribe(Collection> channels, RedisMessageHandler handler); - - /** - * Subscribes to namespace-confined patterns. - * - * @param patterns the patterns - * @param handler the message callback - * @param the message type - * @return the subscription handle - */ - Subscription patternSubscribe( - Collection> patterns, RedisMessageHandler handler); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisShardedPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisShardedPubSubOperations.java deleted file mode 100644 index 7e43982d..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/RedisShardedPubSubOperations.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -import java.util.Collection; - -/** - * Sharded Pub/Sub operations. - * - *

Preferred on Cluster because delivery is confined to the shard owning the channel slot instead - * of being broadcast to every node. Delivery is still at-most-once. - */ -public interface RedisShardedPubSubOperations { - - /** - * Publishes a message to the owning shard. - * - * @param channel the channel - * @param message the message - * @param the message type - * @return the number of clients that received the message - */ - long publish(ShardedPubSubChannel channel, V message); - - /** - * Subscribes to sharded channels. - * - * @param channels the channels - * @param handler the message callback - * @param the message type - * @return the subscription handle - */ - Subscription subscribe( - Collection> channels, RedisMessageHandler handler); -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ScoreRange.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ScoreRange.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ScoreRange.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ScoreRange.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ShardedPubSubChannel.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ShardedPubSubChannel.java deleted file mode 100644 index adc28a89..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ShardedPubSubChannel.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import java.util.Objects; - -/** - * A namespaced sharded Pub/Sub channel. - * - *

On Cluster this is the default, because ordinary Pub/Sub broadcasts to every node and its cost - * grows with cluster size. - * - * @param namespace the owning namespace - * @param name the channel name - * @param messageCodec codec for published messages - * @param the message type - */ -public record ShardedPubSubChannel( - RedisNamespace namespace, RedisKeyName name, RedisCodec messageCodec) { - - public ShardedPubSubChannel { - Objects.requireNonNull(namespace, "namespace must be non-null"); - Objects.requireNonNull(name, "name must be non-null"); - Objects.requireNonNull(messageCodec, "message codec must be non-null"); - } - - /** - * Renders the physical channel name. - * - * @return the rendered channel - */ - public String render() { - return namespace.prefix() + ':' + name.entity() + ':' + name.identifier(); - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortDirection.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortDirection.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortDirection.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortDirection.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortedSetAddOptions.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortedSetAddOptions.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortedSetAddOptions.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/SortedSetAddOptions.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamAppendOptions.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamAppendOptions.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamAppendOptions.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamAppendOptions.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamConsumer.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamConsumer.java index f163ed9e..3c8e4c55 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamConsumer.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamConsumer.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; /** * Consumer name inside a group. diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionOutcome.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionOutcome.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionOutcome.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionOutcome.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionPolicy.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionPolicy.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionPolicy.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamDeletionPolicy.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamGroup.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamGroup.java index bba4693f..51b81d09 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamGroup.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamGroup.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; /** * Consumer group name. diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamId.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamId.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamId.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamId.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamTrimPolicy.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamTrimPolicy.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamTrimPolicy.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/StreamTrimPolicy.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Subscription.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Subscription.java deleted file mode 100644 index e2fe27f1..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/Subscription.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -/** - * Handle to an active subscription. - * - *

Closing releases the dedicated Pub/Sub connection. A subscription that is never closed leaks a - * connection, which is why this is {@link AutoCloseable} rather than a fire-and-forget call. - */ -public interface Subscription extends AutoCloseable { - - /** - * Reports whether the subscription is still active. - * - * @return {@code true} while the subscription is delivering - */ - boolean active(); - - /** - * Returns the rendered channels or patterns this subscription covers. - * - * @return the subscribed targets - */ - java.util.List targets(); - - @Override - void close(); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisPubSubOperations.java deleted file mode 100644 index 8f8c69eb..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisPubSubOperations.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubPattern; -import java.util.Collection; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Reactive Pub/Sub operations. - * - *

Delivery is at-most-once. Cancelling a subscription publisher unsubscribes and releases the - * dedicated connection. - */ -public interface ReactiveRedisPubSubOperations { - - /** - * Publishes a message. - * - * @param channel the channel - * @param message the message - * @param the message type - * @return the number of clients that received the message - */ - Mono publish(PubSubChannel channel, V message); - - /** - * Subscribes to channels. - * - * @param channels the channels - * @param the message type - * @return the received messages until the publisher is cancelled - */ - Flux subscribe(Collection> channels); - - /** - * Subscribes to namespace-confined patterns. - * - * @param patterns the patterns - * @param the message type - * @return the received messages until the publisher is cancelled - */ - Flux patternSubscribe(Collection> patterns); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisShardedPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisShardedPubSubOperations.java deleted file mode 100644 index 1b61d246..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/reactive/ReactiveRedisShardedPubSubOperations.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ShardedPubSubChannel; -import java.util.Collection; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** Reactive sharded Pub/Sub operations; preferred on Cluster. */ -public interface ReactiveRedisShardedPubSubOperations { - - /** - * Publishes a message to the owning shard. - * - * @param channel the channel - * @param message the message - * @param the message type - * @return the number of clients that received the message - */ - Mono publish(ShardedPubSubChannel channel, V message); - - /** - * Subscribes to sharded channels. - * - * @param channels the channels - * @param the message type - * @return the received messages until the publisher is cancelled - */ - Flux subscribe(Collection> channels); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterTopologyObserver.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterTopologyObserver.java index 8b2da0f9..752a7f8d 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterTopologyObserver.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterTopologyObserver.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; import java.util.EnumMap; import java.util.Map; import java.util.Objects; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/SameSlotValidator.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/SameSlotValidator.java index be06a40a..276026b4 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/SameSlotValidator.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/SameSlotValidator.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPermitVerifier.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPermitVerifier.java index e4b23adf..d3953912 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPermitVerifier.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/ConfiguredRedisPermitVerifier.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOperationPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbe.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbe.java index f31e3704..6d117494 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbe.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbe.java @@ -1,8 +1,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; @@ -31,7 +31,6 @@ public final class RedisCapabilityProbe { private static Map> witnessCommands() { Map> witnesses = new EnumMap<>(RedisCapability.class); - witnesses.put(RedisCapability.SHARDED_PUBSUB, List.of(CommandId.of("SPUBLISH"))); witnesses.put(RedisCapability.FUNCTIONS, List.of(CommandId.of("FCALL"))); witnesses.put(RedisCapability.HASH_FIELD_EXPIRATION, List.of(CommandId.of("HEXPIRE"))); witnesses.put(RedisCapability.HASH_FIELD_EXPIRATION_COMBINED, List.of(CommandId.of("HGETEX"))); diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbe.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbe.java index 45cbb43d..67053d8e 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbe.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbe.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; @@ -50,7 +51,7 @@ public final class RedisStartupProbe { * @return the confirmed capability snapshot */ public RedisCapabilities confirm( - RedisSdkSettings settings, + RedisRuntimeSettings settings, ServerFacts serverFacts, Collection requiredCapabilities) { return confirm(settings, serverFacts, requiredCapabilities, false); @@ -67,7 +68,7 @@ public final class RedisStartupProbe { * @return the confirmed capability snapshot */ public RedisCapabilities confirm( - RedisSdkSettings settings, + RedisRuntimeSettings settings, ServerFacts serverFacts, Collection requiredCapabilities, boolean acknowledgedWriteLossAccepted) { diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/DoubleCodec.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/DoubleCodec.java index 2dc49adb..0ecde59d 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/DoubleCodec.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/DoubleCodec.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/JsonEnvelopeFraming.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/JsonEnvelopeFraming.java index 32a4a8ac..6fe42272 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/JsonEnvelopeFraming.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/JsonEnvelopeFraming.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisEnvelope; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/LongCodec.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/LongCodec.java index 89d996cd..d2ffdd6a 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/LongCodec.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/LongCodec.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistry.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistry.java index 77f6e2e5..39ab1f25 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistry.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistry.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisPayloadCodec; import java.time.Clock; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodec.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodec.java index fa5ffcfc..0821b19a 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodec.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodec.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisEnvelope; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisPayloadCodec; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandAdmission.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandAdmission.java index 7a2f709f..aeb8ce4b 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandAdmission.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandAdmission.java @@ -1,7 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisCommandDescriptor; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; import java.time.Duration; import java.util.Objects; import java.util.OptionalInt; @@ -16,7 +16,7 @@ import java.util.OptionalInt; */ public record CommandAdmission( RedisCommandDescriptor descriptor, - RedisConnectionKind connectionKind, + RedisLane connectionKind, OptionalInt slot, Duration timeout) { diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandExecutionContext.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandExecutionContext.java index fa34b73b..9c3b769a 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandExecutionContext.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandExecutionContext.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuard.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuard.java index 70d95703..2a1e2a58 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuard.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuard.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandSupport; @@ -12,7 +13,6 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotE import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import java.time.Duration; import java.util.HashSet; import java.util.Objects; @@ -100,8 +100,8 @@ public final class CommandPolicyGuard { return new CommandAdmission( policy.descriptor(), - dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind - .forCommand(policy.descriptor()), + dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisSdkLane.forCommand( + policy.descriptor()), slot, timeout); } diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/QueueingRedisCommandExecutor.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/QueueingRedisCommandExecutor.java index f3134a23..b59639d8 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/QueueingRedisCommandExecutor.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/QueueingRedisCommandExecutor.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability.NoThrowObservationSink; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability.RedisObservation; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ReactiveRedisCommandExecutor.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ReactiveRedisCommandExecutor.java index 7e51cf05..16634545 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ReactiveRedisCommandExecutor.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ReactiveRedisCommandExecutor.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability.NoThrowObservationSink; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability.RedisObservation; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandCatalog.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandCatalog.java index b9e63268..a9cf156f 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandCatalog.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandCatalog.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandSupport; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/SyncRedisCommandExecutor.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/SyncRedisCommandExecutor.java index 977f8e89..4d83eb37 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/SyncRedisCommandExecutor.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/SyncRedisCommandExecutor.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability.NoThrowObservationSink; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability.RedisObservation; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkComposition.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkComposition.java new file mode 100644 index 00000000..c3ac8d26 --- /dev/null +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkComposition.java @@ -0,0 +1,88 @@ +package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisAccountContribution; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisLaneContribution; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; + +/** + * What the typed SDK contributes to the Redis runtime: its lanes' ceilings and its admin account. + * + *

The SDK is a library and composes nothing by itself. A service that uses its blocking, + * transaction or admin surfaces declares one bean per lane it uses in its own adapter's + * configuration — the runtime collects {@link RedisLaneContribution} and {@link + * RedisAccountContribution} beans and pools, drains and authenticates them like its own: + * + *

{@code
+ * @Bean RedisLaneContribution redisBlockingLane() { return RedisSdkComposition.blockingLane(32); }
+ * @Bean RedisLaneContribution redisTransactionLane() { return RedisSdkComposition.transactionLane(16); }
+ * @Bean RedisLaneContribution redisAdminLane() { return RedisSdkComposition.adminLane(); }
+ * @Bean RedisAccountContribution redisAdminAccount() {
+ *   return RedisSdkComposition.adminAccount("secret://ca-skeleton-admin@environment/APP_REDIS_ADMIN");
+ * }
+ * }
+ * + *

Like the SDK's other knobs (operation limits, enabled policies, raw approvals) these are code, + * not {@code app.redis.*} settings: the runtime's settings describe the runtime, and a lane nobody + * composed has no setting to be wrong about. An admin lane without an admin account runs on the + * application account, which is a decision the service takes by not contributing one. + */ +public final class RedisSdkComposition { + + /** The admin account's name, as the runtime logs it. */ + static final String ADMIN_ACCOUNT_NAME = "admin"; + + /** The read-only diagnostics account the {@link RedisSdkLane#ADMIN} lane authenticates as. */ + public static final RedisAccount ADMIN_ACCOUNT = new RedisAccount(ADMIN_ACCOUNT_NAME); + + /** The blocking lane ceiling the SDK was designed around. */ + public static final int DEFAULT_BLOCKING_CONNECTIONS = 32; + + /** The transaction lane ceiling the SDK was designed around. */ + public static final int DEFAULT_TRANSACTION_CONNECTIONS = 16; + + /** + * Two admin connections: diagnostics are rare, and a second one keeps a slow read from blocking. + */ + private static final int ADMIN_CONNECTIONS = 2; + + private RedisSdkComposition() {} + + /** + * The blocking lane. + * + * @param maximumConnections the ceiling + * @return the contribution + */ + public static RedisLaneContribution blockingLane(int maximumConnections) { + return new RedisLaneContribution(RedisSdkLane.BLOCKING, maximumConnections); + } + + /** + * The transaction lane. + * + * @param maximumConnections the ceiling + * @return the contribution + */ + public static RedisLaneContribution transactionLane(int maximumConnections) { + return new RedisLaneContribution(RedisSdkLane.TRANSACTION, maximumConnections); + } + + /** + * The admin lane. + * + * @return the contribution + */ + public static RedisLaneContribution adminLane() { + return new RedisLaneContribution(RedisSdkLane.ADMIN, ADMIN_CONNECTIONS); + } + + /** + * The admin account, resolved by the runtime before any client exists. + * + * @param credentialReference the admin account's credential reference + * @return the contribution + */ + public static RedisAccountContribution adminAccount(String credentialReference) { + return new RedisAccountContribution(ADMIN_ACCOUNT, credentialReference); + } +} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkLane.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkLane.java new file mode 100644 index 00000000..3fba6478 --- /dev/null +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisSdkLane.java @@ -0,0 +1,63 @@ +package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; + +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisCommandDescriptor; +import java.util.Objects; + +/** + * The lanes the typed SDK composes on the Redis runtime, beyond the runtime's own. + * + *

The runtime pools {@code REGULAR} and {@code SCRIPT} for its semantic consumers. The SDK needs + * three more, and they are its own: a blocking command holds its connection for the whole block, a + * transaction owns its connection between {@code MULTI} and {@code EXEC} (and on Cluster must run + * on the node that owns its keys), and admin diagnostics run under a read-only account whose grants + * must never reach a request path. {@link RedisSdkComposition} contributes their ceilings and the + * admin account to the runtime. + */ +public enum RedisSdkLane implements RedisLane { + /** Blocking commands on a dedicated bounded pool. */ + BLOCKING(RedisAccount.APPLICATION.name(), false), + /** One exclusive connection per optimistic transaction, pinned to its keys' node on Cluster. */ + TRANSACTION(RedisAccount.APPLICATION.name(), true), + /** Read-only diagnostics under the admin account. */ + ADMIN(RedisSdkComposition.ADMIN_ACCOUNT_NAME, false); + + // Names rather than records: an enum constant's state must be deeply immutable. + private final String account; + private final boolean pinnedToKeyOwner; + + RedisSdkLane(String account, boolean pinnedToKeyOwner) { + this.account = account; + this.pinnedToKeyOwner = pinnedToKeyOwner; + } + + @Override + public RedisAccount account() { + return new RedisAccount(account); + } + + @Override + public boolean pinnedToKeyOwner() { + return pinnedToKeyOwner; + } + + /** + * Selects the lane a descriptor must run on. + * + * @param descriptor the command descriptor + * @return the required lane + */ + public static RedisLane forCommand(RedisCommandDescriptor descriptor) { + Objects.requireNonNull(descriptor, "descriptor must be non-null"); + if (descriptor.blocking()) { + return BLOCKING; + } + return switch (descriptor.access()) { + case ADMIN_READONLY -> ADMIN; + case APPLICATION, APPLICATION_ADVANCED, RAW_GATEWAY, EXTENSION -> RedisConnectionKind.REGULAR; + case NONE -> throw new IllegalArgumentException("a blocked command has no connection lane"); + }; + } +} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservation.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservation.java index d9fa4a2c..74fb78a4 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservation.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservation.java @@ -1,9 +1,9 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisCommandDescriptor; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -39,7 +39,7 @@ public final class RedisObservation { private final CommandId commandId; private final RedisCommandDescriptor descriptor; - private final RedisConnectionKind connectionKind; + private final RedisLane connectionKind; private final RedisDeploymentMode deploymentMode; private final OptionalInt slot; private final String outcome; @@ -49,7 +49,7 @@ public final class RedisObservation { private RedisObservation( CommandId commandId, RedisCommandDescriptor descriptor, - RedisConnectionKind connectionKind, + RedisLane connectionKind, RedisDeploymentMode deploymentMode, OptionalInt slot, String outcome, @@ -76,7 +76,7 @@ public final class RedisObservation { */ public static RedisObservation starting( RedisCommandDescriptor descriptor, - RedisConnectionKind connectionKind, + RedisLane connectionKind, RedisDeploymentMode deploymentMode, OptionalInt slot) { Objects.requireNonNull(descriptor, "descriptor must be non-null"); diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/BatchExecution.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/BatchExecution.java index ebdd761f..02d199e2 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/BatchExecution.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/BatchExecution.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/GeoSearchHit.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/GeoSearchHit.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/GeoSearchHit.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/GeoSearchHit.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/HashScanPage.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/HashScanPage.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/HashScanPage.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/HashScanPage.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyScanPage.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyScanPage.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyScanPage.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyScanPage.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyedElement.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyedElement.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyedElement.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/KeyedElement.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisBatchOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisBatchOperations.java index a07568c8..27e5e61f 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisBatchOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisBatchOperations.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BatchOptions; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBatch; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBatchResult; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisPubSubOperations.java deleted file mode 100644 index c4861b86..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisPubSubOperations.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubPattern; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisPubSubOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.ReactiveRedisCommandExecutor; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Reactive publish and subscribe. - * - *

A subscription becomes a {@link Flux} whose cancellation closes the driver handle, so an - * abandoned subscriber releases its pub/sub connection instead of leaking it. - */ -public final class LettuceReactiveRedisPubSubOperations implements ReactiveRedisPubSubOperations { - - private final PubSubOperationRequests requests; - - private final RedisPubSubGateway gateway; - - private final ReactiveRedisCommandExecutor executor; - - /** - * Creates the reactive pub/sub operations. - * - * @param pubSubGateway the driver seam, bound to a pub/sub-lane connection - * @param context the shared rendering, permit, and budget rules - * @param executor the guarded reactive executor - */ - public LettuceReactiveRedisPubSubOperations( - RedisPubSubGateway pubSubGateway, - RedisOperationContext context, - ReactiveRedisCommandExecutor executor) { - this.requests = new PubSubOperationRequests(pubSubGateway, context); - this.gateway = Objects.requireNonNull(pubSubGateway, "pub/sub gateway must be non-null"); - this.executor = Objects.requireNonNull(executor, "executor must be non-null"); - } - - @Override - public Mono publish(PubSubChannel channel, V message) { - return executor.execute(requests.publish(channel, message)); - } - - @Override - public Flux subscribe(Collection> channels) { - List targets = requests.channelTargets(channels); - // One codec per channel, not the first channel's codec for all of them — the same rule the - // blocking subscription already enforces. Until this matched, a two-channel subscription - // decoded correctly through RedisPubSubOperations and silently reinterpreted the second - // channel's payload under the first channel's schema through this one. - Map> codecsByChannel = new HashMap<>(); - for (PubSubChannel channel : channels) { - codecsByChannel.put(channel.render(), channel.messageCodec()); - } - return SubscriptionFlux.createPerChannel( - gateway, targets, RedisPubSubGateway.SubscriptionKind.CHANNEL, codecsByChannel); - } - - @Override - public Flux patternSubscribe(Collection> patterns) { - List targets = requests.patternTargets(patterns); - // A matched message carries its concrete channel, not the pattern that matched it, so there is - // no key to look a per-pattern codec up by. Mixed codecs are refused rather than guessed, which - // is what the blocking pattern subscription already does. - RedisCodec codec = PubSubCodecs.singlePatternCodec(patterns); - return SubscriptionFlux.create( - gateway, targets, RedisPubSubGateway.SubscriptionKind.PATTERN, codec); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisShardedPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisShardedPubSubOperations.java deleted file mode 100644 index c6953a96..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisShardedPubSubOperations.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ShardedPubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisShardedPubSubOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.ReactiveRedisCommandExecutor; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** Reactive sharded pub/sub, available only from Redis 7.0. */ -public final class LettuceReactiveRedisShardedPubSubOperations - implements ReactiveRedisShardedPubSubOperations { - - private final PubSubOperationRequests requests; - - private final RedisPubSubGateway gateway; - - private final ReactiveRedisCommandExecutor executor; - - private LettuceReactiveRedisShardedPubSubOperations( - RedisPubSubGateway gateway, - RedisOperationContext context, - ReactiveRedisCommandExecutor executor) { - this.requests = new PubSubOperationRequests(gateway, context); - this.gateway = gateway; - this.executor = Objects.requireNonNull(executor, "executor must be non-null"); - } - - /** - * Creates the capability when the probed server supports sharded pub/sub. - * - * @param capabilities the probed server capabilities - * @param gateway the driver seam, bound to a pub/sub-lane connection - * @param context the shared rendering, permit, and budget rules - * @param executor the guarded reactive executor - * @return the operations, or empty on a server below Redis 7.0 - */ - public static Optional ifSupported( - RedisCapabilities capabilities, - RedisPubSubGateway gateway, - RedisOperationContext context, - ReactiveRedisCommandExecutor executor) { - Objects.requireNonNull(capabilities, "capabilities must be non-null"); - if (!capabilities.has(RedisCapability.SHARDED_PUBSUB)) { - return Optional.empty(); - } - return Optional.of(new LettuceReactiveRedisShardedPubSubOperations(gateway, context, executor)); - } - - @Override - public Mono publish(ShardedPubSubChannel channel, V message) { - return executor.execute(requests.publishSharded(channel, message)); - } - - @Override - public Flux subscribe(Collection> channels) { - List targets = requests.shardTargets(channels); - // One codec per channel, for the same reason as every other channel subscription here: the - // first channel's codec applied to all of them reinterprets the other channels' payloads under - // the wrong schema, and does it silently whenever the framings happen to be compatible. - Map> codecsByChannel = new HashMap<>(); - for (ShardedPubSubChannel channel : channels) { - codecsByChannel.put(channel.render(), channel.messageCodec()); - } - return SubscriptionFlux.createPerChannel( - gateway, targets, RedisPubSubGateway.SubscriptionKind.SHARD, codecsByChannel); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisValueOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisValueOperations.java index fe00fbce..73916d57 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisValueOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceReactiveRedisValueOperations.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.OperationBudget; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.ValueKey; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatch.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatch.java index 876157ce..889f504d 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatch.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatch.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOperationPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.OperationBudget; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatchOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatchOperations.java index 4ba7fb5f..9620e110 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatchOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBatchOperations.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BatchOptions; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBatch; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBatchOperations; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingListOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingListOperations.java index 8ab8e6d8..31dca261 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingListOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingListOperations.java @@ -17,7 +17,7 @@ import java.util.Optional; *

Design section 10.3 requires a separate bean with a dedicated pool, because a command that * occupies its connection until the server answers would otherwise starve ordinary traffic. That is * why this type takes its own gateway: the composition root binds it to a connection borrowed from - * {@code RedisConnectionKind.BLOCKING}, never the regular lane the other operations share. + * {@code RedisSdkLane.BLOCKING}, never the regular lane the other operations share. * *

An unbounded wait is impossible here. The request always declares its block, {@code * CommandPolicyGuard} refuses a non-positive or over-ceiling one, and the client timeout is the diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingStreamOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingStreamOperations.java index 76c96cc1..ca6920f7 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingStreamOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisBlockingStreamOperations.java @@ -16,8 +16,8 @@ import java.util.Objects; * *

Design section 10.9 puts these on a dedicated pool for the same reason as the blocking list * pops: a read that holds its connection until an entry arrives would otherwise starve ordinary - * traffic. That is why this type takes its own gateway, bound to a {@code - * RedisConnectionKind.BLOCKING} connection. + * traffic. That is why this type takes its own gateway, bound to a {@code RedisSdkLane.BLOCKING} + * connection. * *

{@code XREAD} is the same command name as the non-blocking read, so the catalog marks its * block optional. Here the block is mandatory — the parameter is not nullable, and the guard diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java similarity index 97% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java index 7e5ead5e..71c83c48 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisCommandGateway.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisDriverConnection; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BitFieldOverflow; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BitFieldSubcommand; @@ -117,6 +119,28 @@ public final class LettuceRedisCommandGateway implements RedisCommandGateway { this.transactional = null; } + private LettuceRedisCommandGateway( + RedisClusterAsyncCommands commands, + RedisAsyncCommands transactional) { + this.commands = commands; + this.transactional = transactional; + } + + /** + * Creates a gateway over a connection borrowed from the Redis runtime. + * + *

A single-node connection — standalone, Sentinel, or a Cluster lane pinned to its keys' node + * — can own a transaction window; a slot-routing Cluster connection cannot, and the gateway says + * so rather than failing halfway through one. + * + * @param driver the borrowed connection's driver surface + * @return the gateway + */ + public static LettuceRedisCommandGateway over(RedisDriverConnection driver) { + Objects.requireNonNull(driver, "driver connection must be non-null"); + return new LettuceRedisCommandGateway(driver.commands(), driver.transactional().orElse(null)); + } + private RedisAsyncCommands requireTransactional() { if (transactional == null) { throw new IllegalStateException( diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisPubSubOperations.java deleted file mode 100644 index 2bb90938..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisPubSubOperations.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubPattern; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisMessageHandler; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisPubSubOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Subscription; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.SyncRedisCommandExecutor; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Blocking publish and subscribe. - * - *

Publishing is guarded like any other command. Subscribing is not a command with a reply, so it - * takes the dedicated pub/sub gateway and returns a {@link Subscription} the caller must close; - * nothing here can occupy the lane ordinary commands use. - */ -public final class LettuceRedisPubSubOperations implements RedisPubSubOperations { - - private final PubSubOperationRequests requests; - - private final RedisPubSubGateway gateway; - - private final SyncRedisCommandExecutor executor; - - /** - * Creates the pub/sub operations. - * - * @param pubSubGateway the driver seam, bound to a pub/sub-lane connection - * @param context the shared rendering, permit, and budget rules - * @param executor the guarded blocking executor - */ - public LettuceRedisPubSubOperations( - RedisPubSubGateway pubSubGateway, - RedisOperationContext context, - SyncRedisCommandExecutor executor) { - this.requests = new PubSubOperationRequests(pubSubGateway, context); - this.gateway = Objects.requireNonNull(pubSubGateway, "pub/sub gateway must be non-null"); - this.executor = Objects.requireNonNull(executor, "executor must be non-null"); - } - - @Override - public long publish(PubSubChannel channel, V message) { - return executor.execute(requests.publish(channel, message)); - } - - @Override - public Subscription subscribe( - Collection> channels, RedisMessageHandler handler) { - Objects.requireNonNull(handler, "handler must be non-null"); - List targets = requests.channelTargets(channels); - // One codec per channel, not the first channel's codec for all of them. A subscription that - // mixes channels used to decode every message with whichever codec happened to be first, so - // the payloads of the other channels were reinterpreted under the wrong schema — silently, - // when the framings happened to be compatible. - Map> codecsByChannel = new HashMap<>(); - for (PubSubChannel channel : channels) { - codecsByChannel.put(channel.render(), channel.messageCodec()); - } - return LiveSubscription.start( - gateway, - targets, - RedisPubSubGateway.SubscriptionKind.CHANNEL, - (channel, payload) -> { - RedisCodec codec = codecsByChannel.get(channel); - if (codec == null) { - // The server delivered a channel this subscription never asked for. Guessing a codec - // here is how a mis-routed message becomes a decoded object. - throw new IllegalStateException( - "received a message for channel '" - + channel - + "' which this subscription did" - + " not subscribe to"); - } - handler.onMessage(channel, codec.decode(payload)); - }); - } - - @Override - public Subscription patternSubscribe( - Collection> patterns, RedisMessageHandler handler) { - Objects.requireNonNull(handler, "handler must be non-null"); - List targets = requests.patternTargets(patterns); - // A pattern subscription is delivered with the *concrete* channel name, not the pattern that - // matched it, so there is no key to look a per-pattern codec up by. Rather than pick one and - // hope, the patterns are required to agree on their codec; mixing schemas across patterns is a - // decode the SDK cannot perform correctly and so refuses to attempt. - RedisCodec codec = PubSubCodecs.singlePatternCodec(patterns); - return LiveSubscription.start( - gateway, - targets, - RedisPubSubGateway.SubscriptionKind.PATTERN, - (channel, payload) -> handler.onMessage(channel, codec.decode(payload))); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisShardedPubSubOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisShardedPubSubOperations.java deleted file mode 100644 index 47f7797b..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisShardedPubSubOperations.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisMessageHandler; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisShardedPubSubOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ShardedPubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Subscription; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.SyncRedisCommandExecutor; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Sharded publish and subscribe, available only from Redis 7.0. - * - *

Gated the same way per-field expiry is: {@link #ifSupported} yields nothing below 7.0 so there - * is no instance to inject, and {@code SPUBLISH} carries the same minimum in the policy catalog so - * the guard refuses it independently. - */ -public final class LettuceRedisShardedPubSubOperations implements RedisShardedPubSubOperations { - - private final PubSubOperationRequests requests; - - private final RedisPubSubGateway gateway; - - private final SyncRedisCommandExecutor executor; - - private LettuceRedisShardedPubSubOperations( - RedisPubSubGateway gateway, - RedisOperationContext context, - SyncRedisCommandExecutor executor) { - this.requests = new PubSubOperationRequests(gateway, context); - this.gateway = gateway; - this.executor = Objects.requireNonNull(executor, "executor must be non-null"); - } - - /** - * Creates the capability when the probed server supports sharded pub/sub. - * - * @param capabilities the probed server capabilities - * @param gateway the driver seam, bound to a pub/sub-lane connection - * @param context the shared rendering, permit, and budget rules - * @param executor the guarded blocking executor - * @return the operations, or empty on a server below Redis 7.0 - */ - public static Optional ifSupported( - RedisCapabilities capabilities, - RedisPubSubGateway gateway, - RedisOperationContext context, - SyncRedisCommandExecutor executor) { - Objects.requireNonNull(capabilities, "capabilities must be non-null"); - if (!capabilities.has(RedisCapability.SHARDED_PUBSUB)) { - return Optional.empty(); - } - return Optional.of(new LettuceRedisShardedPubSubOperations(gateway, context, executor)); - } - - @Override - public long publish(ShardedPubSubChannel channel, V message) { - return executor.execute(requests.publishSharded(channel, message)); - } - - @Override - public Subscription subscribe( - Collection> channels, RedisMessageHandler handler) { - Objects.requireNonNull(handler, "handler must be non-null"); - List targets = requests.shardTargets(channels); - // One codec per channel, not the first channel's codec for all of them. The blocking channel - // subscription fixed this and this one did not, so the same two-channel subscription decoded - // correctly on one API and silently reinterpreted the second channel's payload under the first - // channel's schema on the other — whenever the two framings happened to be compatible. - Map> codecsByChannel = new HashMap<>(); - for (ShardedPubSubChannel channel : channels) { - codecsByChannel.put(channel.render(), channel.messageCodec()); - } - return LiveSubscription.start( - gateway, - targets, - RedisPubSubGateway.SubscriptionKind.SHARD, - (channel, payload) -> { - RedisCodec codec = codecsByChannel.get(channel); - if (codec == null) { - // The server delivered a channel this subscription never asked for. Guessing a codec - // here is how a mis-routed message becomes a decoded object. - throw new IllegalStateException( - "received a message for shard channel '" - + channel - + "' which this subscription did not subscribe to"); - } - handler.onMessage(channel, codec.decode(payload)); - }); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisValueOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisValueOperations.java index e371ddaf..6b2a6853 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisValueOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LettuceRedisValueOperations.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.OperationBudget; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.ValueKey; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveSubscription.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveSubscription.java deleted file mode 100644 index a24b04c7..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveSubscription.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Subscription; -import java.util.List; -import java.util.Objects; -import java.util.function.BiConsumer; - -/** A {@link Subscription} over a driver handle. */ -final class LiveSubscription implements Subscription { - - private final RedisPubSubGateway.RedisSubscriptionHandle handle; - - private final List targets; - - private LiveSubscription( - RedisPubSubGateway.RedisSubscriptionHandle handle, List targets) { - this.handle = handle; - this.targets = targets; - } - - static Subscription start( - RedisPubSubGateway gateway, - List targets, - RedisPubSubGateway.SubscriptionKind kind, - BiConsumer listener) { - Objects.requireNonNull(gateway, "pub/sub gateway must be non-null"); - return new LiveSubscription(gateway.subscribe(targets, kind, listener), targets); - } - - @Override - public boolean active() { - return handle.active(); - } - - @Override - public List targets() { - return targets; - } - - @Override - public void close() { - handle.close(); - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/MemberScanPage.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/MemberScanPage.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/MemberScanPage.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/MemberScanPage.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubCodecs.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubCodecs.java deleted file mode 100644 index 6cd8bbba..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubCodecs.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubPattern; -import java.util.Collection; - -/** - * Codec selection rules shared by the blocking and reactive pub/sub surfaces. - * - *

The two surfaces used to answer "which codec decodes this message" differently — the blocking - * one per channel, the reactive one with whichever channel happened to be first — so the same - * two-channel subscription was correct through one API and silently wrong through the other. The - * rules live here so that difference cannot reappear one implementation at a time. - */ -final class PubSubCodecs { - - private PubSubCodecs() {} - - /** - * Returns the one codec every pattern in a pattern subscription agrees on. - * - *

A matched message arrives with its concrete channel name rather than the pattern that - * matched it, so there is no key to look a per-pattern codec up by. Mixing schemas across - * patterns is a decode the SDK cannot perform correctly, so it refuses rather than picking one. - * - * @throws IllegalArgumentException when the patterns do not agree on a codec - */ - static RedisCodec singlePatternCodec(Collection> patterns) { - RedisCodec codec = patterns.iterator().next().messageCodec(); - for (PubSubPattern pattern : patterns) { - if (!pattern.messageCodec().id().equals(codec.id())) { - throw new IllegalArgumentException( - "a pattern subscription must use one codec for every pattern, but found '" - + codec.id() - + "' and '" - + pattern.messageCodec().id() - + "'; a matched message carries its channel, not its pattern, so the SDK cannot" - + " tell which codec applies. Subscribe once per codec instead."); - } - } - return codec; - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubOperationRequests.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubOperationRequests.java deleted file mode 100644 index ebde9ccf..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/PubSubOperationRequests.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubPattern; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ShardedPubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.CommandRequest; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * Builds the guarded request behind a publish, and validates subscription targets. - * - *

Publishing is an ordinary command and goes through the guard. Subscribing is not: it has no - * reply to bound and no timeout to apply, so what the guard would have checked is checked here — - * the namespace of every target, and the R2 permit a pattern subscription needs because its fan-out - * is decided by the server, not by the request. - */ -final class PubSubOperationRequests { - - private static final String FAMILY = "PUBSUB"; - - private final RedisPubSubGateway gateway; - - private final RedisOperationContext context; - - PubSubOperationRequests(RedisPubSubGateway gateway, RedisOperationContext context) { - this.gateway = Objects.requireNonNull(gateway, "pub/sub gateway must be non-null"); - this.context = Objects.requireNonNull(context, "operation context must be non-null"); - } - - CommandRequest publish(PubSubChannel channel, V message) { - Objects.requireNonNull(channel, "channel must be non-null"); - requireNamespace(channel.namespace()); - byte[] rendered = channel.render().getBytes(StandardCharsets.UTF_8); - byte[] payload = context.encode(channel.messageCodec(), message, FAMILY); - return new CommandRequest<>( - CommandId.parse("PUBLISH"), - List.of(), - (long) rendered.length + payload.length, - 0L, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - () -> gateway.publish(rendered, payload)); - } - - CommandRequest publishSharded(ShardedPubSubChannel channel, V message) { - Objects.requireNonNull(channel, "channel must be non-null"); - requireNamespace(channel.namespace()); - byte[] rendered = channel.render().getBytes(StandardCharsets.UTF_8); - byte[] payload = context.encode(channel.messageCodec(), message, FAMILY); - return new CommandRequest<>( - CommandId.parse("SPUBLISH"), - List.of(), - (long) rendered.length + payload.length, - 0L, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - () -> gateway.publishSharded(rendered, payload)); - } - - List channelTargets(Collection> channels) { - Objects.requireNonNull(channels, "channels must be non-null"); - if (channels.isEmpty()) { - throw context.reject(FAMILY, true, "a subscription needs at least one channel"); - } - List targets = new ArrayList<>(channels.size()); - for (PubSubChannel channel : channels) { - requireNamespace(channel.namespace()); - targets.add(channel.render()); - } - return List.copyOf(targets); - } - - List shardTargets(Collection> channels) { - Objects.requireNonNull(channels, "channels must be non-null"); - if (channels.isEmpty()) { - throw context.reject(FAMILY, true, "a subscription needs at least one channel"); - } - List targets = new ArrayList<>(channels.size()); - for (ShardedPubSubChannel channel : channels) { - requireNamespace(channel.namespace()); - targets.add(channel.render()); - } - return List.copyOf(targets); - } - - List patternTargets(Collection> patterns) { - Objects.requireNonNull(patterns, "patterns must be non-null"); - if (patterns.isEmpty()) { - throw context.reject(FAMILY, true, "a subscription needs at least one pattern"); - } - // PSUBSCRIBE is R2: the server decides how much a pattern matches, so it needs a permit even - // though there is no reply to put a budget on. - context.sdkPermit(RedisOperationContext.PATTERN_SUBSCRIBE); - List targets = new ArrayList<>(patterns.size()); - for (PubSubPattern pattern : patterns) { - requireNamespace(pattern.namespace()); - targets.add(pattern.render()); - } - return List.copyOf(targets); - } - - private void requireNamespace( - dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace namespace) { - if (!namespace.equals(context.namespace())) { - throw context.reject(FAMILY, true, "channel belongs to a namespace this process may not use"); - } - } -} diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java similarity index 97% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java index 0668c6ed..0ce9b01c 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisCommandGateway.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.SemanticRedisCommands; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BitFieldOverflow; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BitFieldSubcommand; @@ -27,7 +29,12 @@ import java.util.Optional; import java.util.concurrent.CompletionStage; /** - * The narrow asynchronous driver surface the typed operations are written against. + * The asynchronous driver surface the typed operations are written against. + * + *

It extends the runtime's {@link SemanticRedisCommands} rather than the runtime carrying this + * surface: the runtime's own consumers need eight commands, and the other hundred-odd are the + * SDK's. The runtime lends the connection ({@code RedisLease.driver()}); {@link + * LettuceRedisCommandGateway#over} turns it into this gateway. * *

Every method names one Redis command and takes already-rendered keys and already-encoded * values. There is deliberately no method that accepts a command name, so the forbidden {@code @@ -38,7 +45,22 @@ import java.util.concurrent.CompletionStage; * permits, budgets, timeouts, and observability are not this interface's concern: everything routed * through it has already passed {@code CommandPolicyGuard}. */ -public interface RedisCommandGateway { +public interface RedisCommandGateway extends SemanticRedisCommands { + + /** + * Writes a value with a relative expiry, as the runtime's semantic commands spell it. + * + * @param key the rendered key + * @param value the encoded value + * @param presence the existence condition + * @param ttl the positive time to live + * @return whether the write was applied + */ + @Override + default CompletionStage set( + byte[] key, byte[] value, WritePresence presence, java.time.Duration ttl) { + return set(key, value, presence, new Expiration.After(ttl)); + } /** * Reads a value. @@ -46,6 +68,7 @@ public interface RedisCommandGateway { * @param key the rendered key * @return the stored bytes, {@code null} when the key does not exist */ + @Override CompletionStage get(byte[] key); /** @@ -86,6 +109,7 @@ public interface RedisCommandGateway { * @param key the rendered key * @return the removed bytes, {@code null} when the key did not exist */ + @Override CompletionStage getAndDelete(byte[] key); /** @@ -104,6 +128,7 @@ public interface RedisCommandGateway { * @param delta the increment * @return the value after the increment */ + @Override CompletionStage incrementBy(byte[] key, long delta); /** @@ -161,6 +186,7 @@ public interface RedisCommandGateway { * * @return the server's reply */ + @Override CompletionStage ping(); /** @@ -1080,6 +1106,7 @@ public interface RedisCommandGateway { * @param source the script source * @return the digest the server assigned */ + @Override CompletionStage loadScript(byte[] source); /** @@ -1165,9 +1192,11 @@ public interface RedisCommandGateway { * @param arguments the script arguments * @return the reply values */ + @Override CompletionStage> evaluateRegisteredForList( String digest, byte[] key, List arguments); + @Override CompletionStage evaluateRegisteredForLong( String digest, byte[] key, List arguments); diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationContext.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationContext.java index 6435d763..89417968 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationContext.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationContext.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOperationPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; @@ -14,7 +15,6 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMet import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisSlotTag; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Expiration; import java.nio.charset.StandardCharsets; @@ -63,9 +63,6 @@ public final class RedisOperationContext { /** Permit policy demanded by {@code BITFIELD}. */ public static final String BITFIELD_EXECUTE = "bitfield-execute"; - /** Permit policy demanded by {@code PSUBSCRIBE}. */ - public static final String PATTERN_SUBSCRIBE = "pattern-subscribe"; - /** Permit policy demanded by a blocking pop or move. */ public static final String BLOCKING_POP = "blocking-pop"; diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ScoredMemberPage.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ScoredMemberPage.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ScoredMemberPage.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ScoredMemberPage.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamClaimPage.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamClaimPage.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamClaimPage.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamClaimPage.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamEntry.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamEntry.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamEntry.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamEntry.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingEntry.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingEntry.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingEntry.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingEntry.java diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingOverview.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingOverview.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingOverview.java rename to src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/StreamPendingOverview.java diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/SubscriptionFlux.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/SubscriptionFlux.java deleted file mode 100644 index 082a8986..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/SubscriptionFlux.java +++ /dev/null @@ -1,163 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import reactor.core.publisher.Flux; -import reactor.core.publisher.FluxSink; - -/** - * Bridges a driver subscription into a {@link Flux} whose cancellation closes it. - * - *

Redis pub/sub has no flow control. The server pushes at whatever rate publishers produce and - * never waits for a consumer, so the only place a slow subscriber can be absorbed is in this - * process. {@code Flux.create} defaults to {@link FluxSink.OverflowStrategy#BUFFER} with an - * unbounded queue, which turns a subscriber that falls behind into heap growth until the JVM dies — - * a cache subscription taking down the whole application is a strictly worse outcome than that - * subscription missing messages. - * - *

So the buffer is bounded and the overflow policy is explicit at the call site. Neither answer - * is right for every caller: an invalidation feed would rather drop the oldest entry and keep - * running, while a feed whose consumer must see every message would rather fail and let the caller - * resubscribe from a known point. What is never right is silently growing forever. - * - *

A decode failure terminates the subscription with an error rather than being swallowed: a - * payload that does not decode means the channel is carrying something this subscriber does not - * understand, and continuing to consume it would hide that. Termination and cancellation both run - * the same disposal path, so the driver subscription is closed and its connection released exactly - * once on every exit. - */ -final class SubscriptionFlux { - - /** Default in-process buffer for one subscription, in messages. */ - static final int DEFAULT_BUFFER_CAPACITY = 1_024; - - private SubscriptionFlux() {} - - static Flux create( - RedisPubSubGateway gateway, - List targets, - RedisPubSubGateway.SubscriptionKind kind, - RedisCodec codec) { - return create(gateway, targets, kind, codec, DEFAULT_BUFFER_CAPACITY, OverflowPolicy.ERROR); - } - - /** - * Creates a channel subscription that decodes each message with the codec its own channel - * declared. - * - *

A subscription that mixes channels used to decode every message with whichever codec - * happened to be first, so the payloads of the other channels were reinterpreted under the wrong - * schema — silently, when the framings happened to be compatible. The blocking API fixed that and - * the reactive one did not, which made correctness depend on which API surface the caller picked. - */ - static Flux createPerChannel( - RedisPubSubGateway gateway, - List targets, - RedisPubSubGateway.SubscriptionKind kind, - Map> codecsByChannel) { - Objects.requireNonNull(gateway, "gateway must be non-null"); - Objects.requireNonNull(targets, "targets must be non-null"); - Objects.requireNonNull(kind, "subscription kind must be non-null"); - Objects.requireNonNull(codecsByChannel, "codecs must be non-null"); - Map> codecs = Map.copyOf(codecsByChannel); - return Flux.create( - sink -> { - RedisPubSubGateway.RedisSubscriptionHandle handle = - gateway.subscribe( - targets, - kind, - (channel, payload) -> { - try { - RedisCodec codec = codecs.get(channel); - if (codec == null) { - // The server delivered a channel this subscription never asked for. - // Guessing a codec here is how a mis-routed message becomes a decoded - // object. - throw new IllegalStateException( - "received a message for channel '" - + channel - + "' which this subscription did not subscribe to"); - } - sink.next(codec.decode(payload)); - } catch (RuntimeException failure) { - // Terminating disposes the sink, which closes the handle below. - sink.error(failure); - } - }); - sink.onDispose(handle::close); - }, - OverflowPolicy.ERROR.strategy()) - .onBackpressureBuffer(DEFAULT_BUFFER_CAPACITY, OverflowPolicy.ERROR.bufferStrategy()); - } - - static Flux create( - RedisPubSubGateway gateway, - List targets, - RedisPubSubGateway.SubscriptionKind kind, - RedisCodec codec, - int bufferCapacity, - OverflowPolicy overflowPolicy) { - Objects.requireNonNull(gateway, "gateway must be non-null"); - Objects.requireNonNull(targets, "targets must be non-null"); - Objects.requireNonNull(kind, "subscription kind must be non-null"); - Objects.requireNonNull(codec, "codec must be non-null"); - Objects.requireNonNull(overflowPolicy, "overflow policy must be non-null"); - if (bufferCapacity < 1) { - throw new IllegalArgumentException("subscription buffer capacity must be positive"); - } - return Flux.create( - sink -> { - RedisPubSubGateway.RedisSubscriptionHandle handle = - gateway.subscribe( - targets, - kind, - (channel, payload) -> { - try { - sink.next(codec.decode(payload)); - } catch (RuntimeException failure) { - // Terminating disposes the sink, which closes the handle below. - sink.error(failure); - } - }); - sink.onDispose(handle::close); - }, - overflowPolicy.strategy()) - .onBackpressureBuffer(bufferCapacity, overflowPolicy.bufferStrategy()); - } - - /** What a subscription does when its consumer cannot keep up. */ - enum OverflowPolicy { - - /** Fail the subscription so the caller learns it fell behind and can resubscribe. */ - ERROR(FluxSink.OverflowStrategy.ERROR, reactor.core.publisher.BufferOverflowStrategy.ERROR), - - /** Keep the newest messages and discard the oldest; for feeds where staleness is the cost. */ - DROP_OLDEST( - FluxSink.OverflowStrategy.LATEST, - reactor.core.publisher.BufferOverflowStrategy.DROP_OLDEST), - - /** Keep the buffered messages and discard arrivals; for feeds where order is the cost. */ - DROP_LATEST( - FluxSink.OverflowStrategy.DROP, reactor.core.publisher.BufferOverflowStrategy.DROP_LATEST); - - private final FluxSink.OverflowStrategy strategy; - private final reactor.core.publisher.BufferOverflowStrategy bufferStrategy; - - OverflowPolicy( - FluxSink.OverflowStrategy strategy, - reactor.core.publisher.BufferOverflowStrategy bufferStrategy) { - this.strategy = strategy; - this.bufferStrategy = bufferStrategy; - } - - FluxSink.OverflowStrategy strategy() { - return strategy; - } - - reactor.core.publisher.BufferOverflowStrategy bufferStrategy() { - return bufferStrategy; - } - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ValueOperationRequests.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ValueOperationRequests.java index 5c8fbb2f..f1038e93 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ValueOperationRequests.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/ValueOperationRequests.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOperationPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LettuceRedisTransactionOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LettuceRedisTransactionOperations.java index 7052138c..710a04b3 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LettuceRedisTransactionOperations.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LettuceRedisTransactionOperations.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.programmability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.HashKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.ListKey; @@ -17,7 +18,6 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.CommandRe import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.QueueingRedisCommandExecutor; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisOperationContext; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.WritePresence; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/RedisTransactionRunner.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/RedisTransactionRunner.java index 398da58e..41cf111c 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/RedisTransactionRunner.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/RedisTransactionRunner.java @@ -1,11 +1,16 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.programmability; +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.cache.redis.sdk.api.command.CommandAccess; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisSlotTag; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisSdkLane; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.LettuceRedisCommandGateway; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; import java.nio.charset.StandardCharsets; import java.util.Collection; @@ -50,7 +55,8 @@ public final class RedisTransactionRunner implements RedisTransactionOperations /** * Creates the runner. * - * @param owner the runtime owner the transaction lane is borrowed from + * @param owner the runtime owner the transaction lane is borrowed from; the service composed + * {@link RedisSdkLane#TRANSACTION} on it * @param renderer renders a watched key so its slot can be computed * @param windowFactory builds the transaction window over a node-scoped gateway */ @@ -121,9 +127,11 @@ public final class RedisTransactionRunner implements RedisTransactionOperations // Only Cluster needs the lane pinned. Asking for a routed lease elsewhere would give up // connection reuse for a decision with one possible answer. Optional routing = routingRequired ? routingKey : Optional.empty(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.TRANSACTION, routing)) { + try (RedisLease lease = borrow(routing)) { try { - return windowFactory.apply(lease.gateway()).watchAndExecute(watched, callback, options); + return windowFactory + .apply(LettuceRedisCommandGateway.over(lease.driver())) + .watchAndExecute(watched, callback, options); } catch (RuntimeException failure) { // A window whose cleanup may not have landed must not be pooled: the next borrower would // queue their command into somebody else's MULTI. @@ -133,6 +141,19 @@ public final class RedisTransactionRunner implements RedisTransactionOperations } } + private RedisLease borrow(Optional routing) { + try { + return owner.borrow(RedisSdkLane.TRANSACTION, routing); + } catch (RedisLaneUnavailableException refused) { + // Raised before any command exists, so the SDK reports it in its own vocabulary as "not + // sent": the caller may retry rather than treat the window as possibly applied. + throw new RedisCommandRejectedException( + refused.getMessage(), + RedisFailureMetadata.notSent("CONNECTION", CommandAccess.NONE, false, owner.mode()), + refused); + } + } + private Optional routingKeyOf(QualifiedRedisKey key) { return Optional.of(renderer.render(key).getBytes(StandardCharsets.UTF_8)); } diff --git a/src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml b/src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml index 1f51d135..571b8e33 100644 --- a/src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml +++ b/src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml @@ -743,38 +743,39 @@ commands: key-spec: "2 2 1" # ---------- pub/sub ---------- + # Blocked: the SDK carries no subscription transport. The typed pub/sub surface was removed + # rather than shipped without a connection that could deliver a message (review G-6b). PUBLISH: risk: R1 - support: TYPED + support: BLOCKED key-spec: "none" SUBSCRIBE: risk: R1 - support: TYPED + support: BLOCKED key-spec: "none" UNSUBSCRIBE: risk: R1 - support: TYPED + support: BLOCKED key-spec: "none" PSUBSCRIBE: risk: R2 - support: ADVANCED_TYPED + support: BLOCKED key-spec: "none" - required-policy: pattern-subscribe PUNSUBSCRIBE: risk: R1 - support: TYPED + support: BLOCKED key-spec: "none" SPUBLISH: risk: R1 - support: VERSION_GATED + support: BLOCKED minimum-version: "7.0" SSUBSCRIBE: risk: R1 - support: VERSION_GATED + support: BLOCKED minimum-version: "7.0" SUNSUBSCRIBE: risk: R1 - support: VERSION_GATED + support: BLOCKED minimum-version: "7.0" PUBSUB CHANNELS: risk: R3 diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java index 4939cf1e..216ab387 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java @@ -32,10 +32,11 @@ class RedisSdkModuleBoundaryTest { private static final Path SDK_RELATIVE_ROOT = Path.of("src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk"); + // The SDK package lives only in redis-sdk: redis-runtime moved to ...cache.redis.runtime + // (S3-#3b), + // so the split package this used to scan across is gone. private static final List SDK_ROOTS = - List.of( - Path.of("../redis-runtime").resolve(SDK_RELATIVE_ROOT), - Path.of("../redis-sdk").resolve(SDK_RELATIVE_ROOT)); + List.of(Path.of("../redis-sdk").resolve(SDK_RELATIVE_ROOT)); private static final String SDK_PACKAGE = "dev.caskeleton.adapter.outbound.cache.redis.sdk"; private static final Pattern IMPORT = Pattern.compile("^import\\s+(?:static\\s+)?([\\w.]+);"); diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java index b60204f5..2926bcc7 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java @@ -33,10 +33,11 @@ class RedisSupportMatrixTest { private static final Path SDK_RELATIVE_ROOT = Path.of("src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk"); + // The SDK package lives only in redis-sdk: redis-runtime moved to ...cache.redis.runtime + // (S3-#3b), + // so the split package this used to scan across is gone. private static final List SDK_ROOTS = - List.of( - Path.of("../redis-runtime").resolve(SDK_RELATIVE_ROOT), - Path.of("../redis-sdk").resolve(SDK_RELATIVE_ROOT)); + List.of(Path.of("../redis-sdk").resolve(SDK_RELATIVE_ROOT)); private static final Path TEST_ROOT = Path.of("src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk"); diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java index 5bb26b53..bbf9b0f0 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandSupport; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java index e308ac80..9b64fa7a 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java @@ -38,14 +38,7 @@ import org.junit.jupiter.api.Test; class ApiParityTest { - /** - * Every typed surface that must exist on both programming models. - * - *

Pub/Sub is intentionally absent: the synchronous API delivers through a handler and returns - * a closeable subscription, while the reactive API delivers through the publisher itself and - * unsubscribes on cancellation. Those are different shapes on purpose, so mechanical parity would - * be the wrong check for them. - */ + /** Every typed surface that must exist on both programming models. */ private static final Map, Class> PAIRS = Map.ofEntries( Map.entry(RedisValueOperations.class, ReactiveRedisValueOperations.class), diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java index 9b4ca28e..7f4e4f7d 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import java.util.List; import org.junit.jupiter.api.Test; @@ -36,7 +37,7 @@ class RedisCapabilitiesTest { RedisCapabilities.of( RedisVersion.parse("7.4.2"), RedisDeploymentMode.SENTINEL, - List.of(RedisCapability.HASH_FIELD_EXPIRATION, RedisCapability.SHARDED_PUBSUB)); + List.of(RedisCapability.HASH_FIELD_EXPIRATION, RedisCapability.FUNCTIONS)); assertThat(capabilities.has(RedisCapability.HASH_FIELD_EXPIRATION)).isTrue(); assertThat(capabilities.has(RedisCapability.STREAM_ACKNOWLEDGE_DELETE)).isFalse(); diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java similarity index 100% rename from src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java index 85767330..7742427f 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java @@ -3,6 +3,8 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.util.Optional; import org.junit.jupiter.api.Test; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java index 5439821e..0f91d144 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import java.util.List; import org.junit.jupiter.api.Test; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java index 06787545..cb9170ba 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java @@ -3,12 +3,13 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisSlotTag; import java.util.List; import org.junit.jupiter.api.DisplayName; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java index 3a266c79..238dc2c8 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java @@ -3,9 +3,9 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCapabilityUnavailableException; @@ -29,7 +29,7 @@ class RedisCapabilityProbeTest { List.of()); assertThat(capabilities.has(RedisCapability.HASH_FIELD_EXPIRATION)).isFalse(); - assertThat(capabilities.has(RedisCapability.SHARDED_PUBSUB)).isTrue(); + assertThat(capabilities.has(RedisCapability.FUNCTIONS)).isTrue(); } @Test diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java index e3ff2763..c110005f 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java @@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOperationPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.PersistentKeyPermit; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java index cd77bf7a..8ec19278 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java @@ -3,9 +3,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCapabilityUnavailableException; import java.util.List; import java.util.Map; @@ -21,7 +22,6 @@ class RedisStartupProbeTest { List.of( "get", "set", - "spublish", "fcall", "hexpire", "hgetex", @@ -32,8 +32,8 @@ class RedisStartupProbeTest { "ts.add", "bf.add"); - private static RedisSdkSettings settings(RedisDeploymentMode mode) { - RedisSdkSettings settings = new RedisSdkSettings(); + private static RedisRuntimeSettings settings(RedisDeploymentMode mode) { + RedisRuntimeSettings settings = new RedisRuntimeSettings(); settings.setMode(mode); return settings; } diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java index 443eef8d..10f194e0 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisPayloadCodec; import java.nio.charset.StandardCharsets; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java index 5e5d6d76..5fd2ac75 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisPayloadCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java index fbe267c5..2e21dc2b 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java @@ -4,9 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.AdvancedOperationPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; @@ -17,12 +20,10 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRej import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.TypedRedisKeys; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisSdkLane; import java.time.Duration; import java.util.List; import java.util.Optional; @@ -249,7 +250,7 @@ class CommandPolicyGuardTest { guard.validate( blockingRequest( Optional.of(Duration.ofSeconds(10)), authority.issueAdvanced("blocking-pop"))); - assertThat(admission.connectionKind()).isEqualTo(RedisConnectionKind.BLOCKING); + assertThat(admission.connectionKind()).isEqualTo(RedisSdkLane.BLOCKING); assertThat(admission.timeout()).isEqualTo(Duration.ofSeconds(12)); } @@ -264,8 +265,7 @@ class CommandPolicyGuardTest { return new CommandPolicyGuard( RedisCommandCatalog.loadDefault(), new ConfiguredRedisPermitVerifier(authority, mode), - RedisCapabilities.of( - RedisVersion.parse("7.2.5"), mode, List.of(RedisCapability.SHARDED_PUBSUB)), + RedisCapabilities.of(RedisVersion.parse("7.2.5"), mode, List.of(RedisCapability.FUNCTIONS)), NAMESPACE, new RedisKeyRenderer(RedisKeyRules.MAX_KEY_BYTES), CommandPolicyGuardTest::testSlot, diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java index af77d26f..54cf6328 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java @@ -4,16 +4,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisOperationException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.TypedRedisKeys; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; @@ -50,7 +50,7 @@ class ObservationIsolationTest { RedisCapabilities.of( RedisVersion.parse("7.2.5"), RedisDeploymentMode.STANDALONE, - List.of(RedisCapability.SHARDED_PUBSUB)), + List.of(RedisCapability.FUNCTIONS)), NAMESPACE, new RedisKeyRenderer(RedisKeyRules.MAX_KEY_BYTES), key -> 0, diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java index daf77cad..ae9ca538 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java @@ -2,11 +2,11 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.observability; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisCommandDescriptor; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.RedisCommandCatalog; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; import java.util.Map; import java.util.OptionalInt; import org.junit.jupiter.api.Test; diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java similarity index 81% rename from src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java index d6924a6f..d71d2376 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.command.WritePresence; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BitFieldOverflow; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.BitFieldSubcommand; @@ -1428,405 +1429,24 @@ final class InMemoryRedisCommandGateway implements RedisCommandGateway { } /** - * Applies the documented effect of the three registered rate-limit programs. - * - *

The fixture does not interpret Lua, so it recognises which program a digest was loaded from - * and applies that program's contract against its own state. Recognition is by a marker unique to - * each source: if a program is edited so its marker no longer matches, this refuses rather than - * silently applying the wrong algorithm — a fixture that quietly evaluates a fixed window when - * the code under test asked for a token bucket would make the test prove nothing. + * Refuses: the programs that answer with an array are the semantic adapters' ({@code + * cache-redis}), and their emulation is the runtime's {@code InMemorySemanticRedisCommands}. */ @Override public CompletionStage> evaluateRegisteredForList( String digest, byte[] key, List arguments) { - String source = scriptSources.get(digest); - if (source == null) { - return CompletableFuture.failedFuture( - new io.lettuce.core.RedisNoScriptException("NOSCRIPT No matching script")); - } - String rendered = text(key); - // The numeric conversion is per-branch, not up front: a lease program's first argument is an - // ownership string, and parsing it as a number turned every lease call into a failure that - // surfaced as "indeterminate" — the one outcome that looks like a legitimate answer. - // Recognition is by a marker unique to each program, and the order is deliberate: the - // idempotency release also deletes its key, so checking the lease release first would run the - // wrong emulation against it. A fixture that quietly evaluates the wrong program is worse than - // one that refuses. - if (source.contains("'tokens'")) { - return done(tokenBucket(rendered, numbers(arguments))); - } - if (source.contains("previous * weight")) { - return done(slidingCounter(rendered, numbers(arguments))); - } - if (source.contains("local windowStart = nowMillis - (nowMillis % windowMillis)")) { - return done(fixedWindow(rendered, numbers(arguments))); - } - if (source.contains("'ACQUIRED'")) { - return done(idempotencyClaim(rendered, arguments)); - } - if (source.contains("'state', ARGV[5], 'rev', rev + 1")) { - return done(idempotencyTransition(rendered, arguments)); - } - if (source.contains("if state ~= 'CLAIMED' then")) { - return done(idempotencyRelease(rendered, arguments)); - } - if (source.contains("mine .. '|'")) { - return done(idempotencyInspect(rendered, arguments)); - } - if (source.contains("redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2])")) { - return done(leaseAcquire(rendered, arguments)); - } - if (source.contains("redis.call('PEXPIRE', KEYS[1], ARGV[2])") - && source.contains("existing ~= ARGV[1]")) { - return done(leaseRenew(rendered, arguments)); - } - if (source.contains("redis.call('DEL', KEYS[1])")) { - return done(leaseRelease(rendered, arguments)); - } - if (source.contains("return {1, redis.call('PTTL', KEYS[1]), existing}")) { - return done(leaseInspect(rendered, arguments)); - } return CompletableFuture.failedFuture( new IllegalStateException( - "the fixture does not recognise this registered program; add its effect rather than" - + " letting it evaluate as another algorithm")); - } - - private String field(String rendered, String name) { - HashEntry entry = hash(rendered).get(name); - return entry == null ? null : text(entry.value); - } - - private void setField(String rendered, String name, String value) { - hash(rendered).put(name, new HashEntry(utf8(value), null)); - } - - private List idempotencyClaim(String rendered, List arguments) { - String ownerToken = text(arguments.get(0)); - String operationId = text(arguments.get(1)); - String fingerprint = text(arguments.get(2)); - long nowMillis = now(); - long leaseTtl = Long.parseLong(text(arguments.get(5))); - String state = field(rendered, "state"); - if (state == null) { - setField(rendered, "state", "CLAIMED"); - setField(rendered, "owner", ownerToken); - setField(rendered, "attempt", "1"); - setField(rendered, "rev", "1"); - setField(rendered, "op", operationId); - setField(rendered, "fp", fingerprint); - setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); - return reply("ACQUIRED", 1, 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); - } - if (!fingerprint.equals(field(rendered, "fp"))) { - return reply("FINGERPRINT_MISMATCH", 0, 0, "", "", ""); - } - long attempt = Long.parseLong(field(rendered, "attempt")); - long rev = Long.parseLong(field(rendered, "rev")); - String owner = field(rendered, "owner"); - String op = field(rendered, "op"); - if ("COMPLETED".equals(state)) { - return reply( - "COMPLETED_REPLAY", - attempt, - rev, - owner, - field(rendered, "resp") == null ? "" : field(rendered, "resp"), - "60000"); - } - if ("ABANDONED".equals(state)) { - return reply("RECOVERY_REQUIRED", attempt, rev, owner, "", ""); - } - if (ownerToken.equals(owner)) { - return operationId.equals(op) - ? reply("REPLAYED_ACQUIRE", attempt, rev, owner, "", field(rendered, "leaseUntil")) - : reply("OWNER_OPERATION_CONFLICT", attempt, rev, owner, "", ""); - } - long leaseUntil = Long.parseLong(field(rendered, "leaseUntil")); - if ("FAILED_RETRYABLE".equals(state) || leaseUntil <= nowMillis) { - setField(rendered, "state", "CLAIMED"); - setField(rendered, "owner", ownerToken); - setField(rendered, "attempt", Long.toString(attempt + 1)); - setField(rendered, "rev", Long.toString(rev + 1)); - setField(rendered, "op", operationId); - setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); - return reply( - "TAKEN_OVER", attempt + 1, rev + 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); - } - return reply("IN_PROGRESS", attempt, rev, owner, "", Long.toString(leaseUntil - nowMillis)); - } - - private List idempotencyTransition(String rendered, List arguments) { - String ownerToken = text(arguments.get(0)); - long expectedRev = Long.parseLong(text(arguments.get(1))); - String operationId = text(arguments.get(2)); - String fromState = text(arguments.get(3)); - String toState = text(arguments.get(4)); - String payload = text(arguments.get(5)); - String leaseUntil = text(arguments.get(6)); - String state = field(rendered, "state"); - if (state == null) { - return reply("ABSENT", 0, 0, "", "", ""); - } - long attempt = Long.parseLong(field(rendered, "attempt")); - long rev = Long.parseLong(field(rendered, "rev")); - String owner = field(rendered, "owner"); - String op = field(rendered, "op"); - if (!ownerToken.equals(owner)) { - return reply("NOT_OWNER", attempt, rev, owner, "", ""); - } - if (!operationId.equals(op)) { - return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); - } - // ALREADY before the revision check, matching the program: a lost reply leaves the caller - // holding the pre-transition revision. - if (state.equals(toState)) { - String stored = field(rendered, "resp"); - return reply("ALREADY", attempt, rev, owner, stored == null ? "" : stored, ""); - } - if (rev != expectedRev) { - return reply("NOT_OWNER", attempt, rev, owner, "", ""); - } - if (!state.equals(fromState)) { - return reply("WRONG_STATE", attempt, rev, owner, state, ""); - } - setField(rendered, "state", toState); - setField(rendered, "rev", Long.toString(rev + 1)); - if (!payload.isEmpty()) { - setField(rendered, "resp", payload); - } - if (!leaseUntil.isEmpty()) { - setField(rendered, "leaseUntil", Long.toString(now() + Long.parseLong(leaseUntil))); - } - return reply("APPLIED", attempt, rev + 1, owner, "", ""); - } - - private List idempotencyRelease(String rendered, List arguments) { - String ownerToken = text(arguments.get(0)); - String operationId = text(arguments.get(2)); - String state = field(rendered, "state"); - if (state == null) { - return reply("ABSENT", 0, 0, "", "", ""); - } - long attempt = Long.parseLong(field(rendered, "attempt")); - long rev = Long.parseLong(field(rendered, "rev")); - String owner = field(rendered, "owner"); - if (!ownerToken.equals(owner)) { - return reply("NOT_OWNER", attempt, rev, owner, "", ""); - } - if (!operationId.equals(field(rendered, "op"))) { - return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); - } - if (!"CLAIMED".equals(state)) { - return reply("WRONG_STATE", attempt, rev, owner, state, ""); - } - hashes.remove(rendered); - return reply("APPLIED", attempt, rev, owner, "", ""); - } - - private List idempotencyInspect(String rendered, List arguments) { - String ownerToken = text(arguments.get(0)); - String fingerprint = text(arguments.get(1)); - String operationId = text(arguments.get(2)); - String state = field(rendered, "state"); - if (state == null) { - return reply("ABSENT", 0, 0, "", "", ""); - } - if (!fingerprint.equals(field(rendered, "fp"))) { - return reply("FINGERPRINT_MISMATCH", 0, 0, "", "", ""); - } - long attempt = Long.parseLong(field(rendered, "attempt")); - long rev = Long.parseLong(field(rendered, "rev")); - String owner = field(rendered, "owner"); - String mine = "OTHER"; - if (ownerToken.equals(owner)) { - mine = operationId.equals(field(rendered, "op")) ? "MINE" : "OPERATION_CONFLICT"; - } - String stored = field(rendered, "resp"); - return reply(state, attempt, rev, owner, stored == null ? "" : stored, mine + "|60000"); - } - - private static List reply( - String status, long attempt, long revision, String owner, String payload, String detail) { - return List.of( - utf8(status), - attempt, - revision, - utf8(owner == null ? "" : owner), - utf8(payload), - utf8(detail)); - } - - private long[] numbers(List arguments) { - return arguments.stream().mapToLong(a -> Long.parseLong(text(a))).toArray(); - } - - private List leaseAcquire(String rendered, List arguments) { - String ownership = text(arguments.get(0)); - long ttlMillis = Long.parseLong(text(arguments.get(1))); - Entry existing = live(rendered); - if (existing == null) { - entries.put(rendered, new Entry(utf8(ownership), now() + ttlMillis)); - return List.of(1L, ttlMillis, utf8("")); - } - String holder = existing.text(); - long remaining = existing.expiresAtMillis == null ? -1 : existing.expiresAtMillis - now(); - return List.of(holder.equals(ownership) ? 2L : 0L, remaining, utf8(holder)); - } - - private List leaseRenew(String rendered, List arguments) { - String ownership = text(arguments.get(0)); - long ttlMillis = Long.parseLong(text(arguments.get(1))); - Entry existing = live(rendered); - if (existing == null) { - return List.of(0L, 0L, utf8("")); - } - String holder = existing.text(); - if (!holder.equals(ownership)) { - return List.of(-1L, existing.expiresAtMillis - now(), utf8(holder)); - } - entries.put(rendered, new Entry(existing.value, now() + ttlMillis)); - return List.of(1L, ttlMillis, utf8(holder)); - } - - private List leaseRelease(String rendered, List arguments) { - String ownership = text(arguments.get(0)); - Entry existing = live(rendered); - if (existing == null) { - return List.of(0L, 0L, utf8("")); - } - String holder = existing.text(); - if (!holder.equals(ownership)) { - return List.of(-1L, existing.expiresAtMillis - now(), utf8(holder)); - } - entries.remove(rendered); - return List.of(1L, 0L, utf8(holder)); - } - - private List leaseInspect(String rendered, List arguments) { - String ownership = text(arguments.get(0)); - Entry existing = live(rendered); - if (existing == null) { - return List.of(0L, 0L, utf8("")); - } - String holder = existing.text(); - long remaining = existing.expiresAtMillis == null ? -1 : existing.expiresAtMillis - now(); - return List.of(holder.equals(ownership) ? 1L : -1L, remaining, utf8(holder)); - } - - private List fixedWindow(String rendered, long[] argv) { - long limit = argv[0]; - long windowMillis = argv[1]; - long cost = argv[2]; - long nowMillis = now(); - long windowStart = nowMillis - Math.floorMod(nowMillis, windowMillis); - long resetAfter = (windowStart + windowMillis) - nowMillis; - // The script's layout: two fields, overwritten when the window turns. - Map fields = hash(rendered); - boolean sameWindow = fields.containsKey("start") && fieldValue(fields, "start") == windowStart; - long current = sameWindow ? fieldValue(fields, "count") : 0; - if (current + cost > limit) { - return List.of(0L, limit - current, resetAfter); - } - fields.put("start", new HashEntry(utf8(Long.toString(windowStart)), null)); - fields.put("count", new HashEntry(utf8(Long.toString(current + cost)), null)); - return List.of(1L, limit - (current + cost), resetAfter); - } - - private List slidingCounter(String rendered, long[] argv) { - long limit = argv[0]; - long windowMillis = argv[1]; - long cost = argv[2]; - long nowMillis = now(); - long windowStart = nowMillis - Math.floorMod(nowMillis, windowMillis); - long elapsed = nowMillis - windowStart; - long resetAfter = windowMillis - elapsed; - // The script's layout: start/cur/prev, rotated when the window turns. - Map fields = hash(rendered); - long storedStart = fields.containsKey("start") ? fieldValue(fields, "start") : Long.MIN_VALUE; - long current = 0; - long previous = 0; - if (storedStart == windowStart) { - current = fieldValue(fields, "cur"); - previous = fieldValue(fields, "prev"); - } else if (storedStart == windowStart - windowMillis) { - previous = fieldValue(fields, "cur"); - } - double weight = (double) (windowMillis - elapsed) / windowMillis; - long estimated = current + (long) Math.floor(previous * weight); - if (estimated + cost > limit) { - return List.of(0L, Math.max(0, limit - estimated), resetAfter); - } - fields.put("start", new HashEntry(utf8(Long.toString(windowStart)), null)); - fields.put("cur", new HashEntry(utf8(Long.toString(current + cost)), null)); - fields.put("prev", new HashEntry(utf8(Long.toString(previous)), null)); - return List.of(1L, Math.max(0, limit - (estimated + cost)), resetAfter); - } - - private List tokenBucket(String rendered, long[] argv) { - long capacity = argv[0]; - long refillTokens = argv[1]; - long refillPeriodMillis = argv[2]; - long cost = argv[3]; - long nowMillis = now(); - Map fields = hash(rendered); - boolean fresh = !fields.containsKey("tokens") || !fields.containsKey("updatedAt"); - long tokens = fresh ? capacity : fieldValue(fields, "tokens"); - long updatedAt = fresh ? nowMillis : fieldValue(fields, "updatedAt"); - if (updatedAt > nowMillis) { - updatedAt = nowMillis; - } - long periods = (nowMillis - updatedAt) / refillPeriodMillis; - if (periods > 0) { - tokens = Math.min(capacity, tokens + (periods * refillTokens)); - updatedAt = updatedAt + (periods * refillPeriodMillis); - } - long resetAfter = refillPeriodMillis - Math.floorMod(nowMillis - updatedAt, refillPeriodMillis); - boolean allowed = tokens >= cost; - if (allowed) { - tokens -= cost; - } - fields.put("tokens", new HashEntry(utf8(Long.toString(tokens)), null)); - fields.put("updatedAt", new HashEntry(utf8(Long.toString(updatedAt)), null)); - return List.of(allowed ? 1L : 0L, tokens, resetAfter); - } - - private static long fieldValue(Map fields, String field) { - HashEntry entry = fields.get(field); - return entry == null ? 0L : Long.parseLong(text(entry.value).strip()); + "the SDK fixture emulates the SDK's own programs; the semantic programs live in the" + + " runtime's InMemorySemanticRedisCommands")); } @Override public CompletionStage evaluateRegisteredForLong( String digest, byte[] key, List arguments) { - String source = scriptSources.get(digest); - if (source != null && source.contains("redis.sha1hex(current)")) { - return done(replaceIfObserved(text(key), arguments)); - } return counter(digest, key, arguments, false).thenApply(Long::parseLong); } - 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)) { - return 0L; - } - long ttlMillis = Long.parseLong(text(arguments.get(2))); - entries.put(rendered, new Entry(arguments.get(1), now() + ttlMillis)); - return 1L; - } - @Override public CompletionStage evaluateRegisteredForValue( String digest, byte[] key, List arguments) { diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java deleted file mode 100644 index 3e8e6565..00000000 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.function.BiConsumer; -import java.util.regex.Pattern; - -/** - * A deterministic in-memory pub/sub bus behind the subscription seam. - * - *

Delivery is synchronous and on the publishing thread, which is what makes the tests - * deterministic. Real fan-out ordering and at-most-once delivery under a disconnect are server - * behaviour and belong to Task 26's evidence. - */ -final class InMemoryRedisPubSubGateway implements RedisPubSubGateway { - - private final List listeners = new ArrayList<>(); - - @Override - public CompletionStage publish(byte[] channel, byte[] message) { - return deliver(new String(channel, StandardCharsets.UTF_8), message, false); - } - - @Override - public CompletionStage publishSharded(byte[] channel, byte[] message) { - return deliver(new String(channel, StandardCharsets.UTF_8), message, true); - } - - @Override - public RedisSubscriptionHandle subscribe( - List targets, SubscriptionKind kind, BiConsumer listener) { - Listener registered = new Listener(List.copyOf(targets), kind, listener); - listeners.add(registered); - return registered; - } - - int activeSubscriptions() { - return (int) listeners.stream().filter(Listener::active).count(); - } - - private CompletionStage deliver(String channel, byte[] message, boolean sharded) { - long delivered = 0L; - for (Listener listener : List.copyOf(listeners)) { - if (listener.accepts(channel, sharded)) { - listener.listener.accept(channel, message.clone()); - delivered++; - } - } - return CompletableFuture.completedFuture(delivered); - } - - private final class Listener implements RedisSubscriptionHandle { - - private final List targets; - - private final SubscriptionKind kind; - - private final BiConsumer listener; - - private boolean open = true; - - private Listener( - List targets, SubscriptionKind kind, BiConsumer listener) { - this.targets = targets; - this.kind = kind; - this.listener = listener; - } - - private boolean accepts(String channel, boolean sharded) { - if (!open) { - return false; - } - if (sharded != (kind == SubscriptionKind.SHARD)) { - return false; - } - if (kind == SubscriptionKind.PATTERN) { - return targets.stream().anyMatch(target -> glob(target).matcher(channel).matches()); - } - return targets.contains(channel); - } - - @Override - public boolean active() { - return open; - } - - @Override - public void close() { - open = false; - listeners.remove(this); - } - } - - private static Pattern glob(String pattern) { - StringBuilder regex = new StringBuilder(pattern.length() + 8); - for (int index = 0; index < pattern.length(); index++) { - char character = pattern.charAt(index); - if (character == '*') { - regex.append(".*"); - } else if (character == '?') { - regex.append('.'); - } else { - regex.append(Pattern.quote(String.valueOf(character))); - } - } - return Pattern.compile(regex.toString()); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java index b86f7253..808c9397 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java @@ -3,14 +3,14 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.MultiKeyPermit; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.ClusterRedirect; import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.ClusterTopologyObserver; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.RedisSlotCalculator; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisCommandExecutionException; import io.lettuce.core.RedisURI; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java index b714df0a..9692fcee 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.OperationBudget; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java index 1bab101e..2e8560c4 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java @@ -1,14 +1,14 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.TypedRedisKeys; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.RedisSlotCalculator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.CommandPolicyGuard; @@ -49,7 +49,6 @@ final class LiveRedisOperationsFixture implements AutoCloseable { RedisOperationContext.BOUNDED_COLLECTION_WRITE, RedisOperationContext.BLOCKING_POP, RedisOperationContext.BITFIELD_EXECUTE, - RedisOperationContext.PATTERN_SUBSCRIBE, RedisOperationContext.STREAM_READ, RedisOperationContext.STREAM_RECOVERY, RedisOperationContext.REGISTERED_SCRIPT, diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java index d5d4004b..d5fde1e4 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.RedisCommandDescriptor; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java index 2bb94f85..d820365e 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.admin.ClientSummary; import dev.caskeleton.adapter.outbound.cache.redis.sdk.admin.LettuceRedisAdminOperations; import dev.caskeleton.adapter.outbound.cache.redis.sdk.admin.SlowLogEntry; @@ -10,7 +11,6 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.RedisCommandCatalog; import java.time.Duration; import java.util.List; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java index 1e534398..5264556b 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java @@ -3,12 +3,12 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.extensions.json.JsonPath; import dev.caskeleton.adapter.outbound.cache.redis.sdk.extensions.json.LettuceRedisJsonOperations; import dev.caskeleton.adapter.outbound.cache.redis.sdk.extensions.probabilistic.LettuceRedisProbabilisticOperations; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java index e122f1b2..75055af7 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java @@ -1,13 +1,13 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.TypedRedisKeys; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; @@ -54,7 +54,6 @@ final class RedisOperationsFixture { RedisOperationContext.STREAM_READ, RedisOperationContext.STREAM_RECOVERY, RedisOperationContext.BITFIELD_EXECUTE, - RedisOperationContext.PATTERN_SUBSCRIBE, RedisOperationContext.REGISTERED_SCRIPT, RedisOperationContext.RAW_COMMAND, "search-index", @@ -125,12 +124,6 @@ final class RedisOperationsFixture { final LettuceReactiveRedisBlockingStreamOperations reactiveBlockingStreams; - final InMemoryRedisPubSubGateway pubSubGateway = new InMemoryRedisPubSubGateway(); - - final LettuceRedisPubSubOperations pubSub; - - final LettuceReactiveRedisPubSubOperations reactivePubSub; - final RedisScriptRegistry scriptRegistry; final LettuceRedisScriptOperations scripts; @@ -215,14 +208,6 @@ final class RedisOperationsFixture { new LettuceReactiveRedisBlockingStreamOperations(gateway, context, reactiveExecutor); this.scriptRegistry = new RedisScriptRegistry(gateway, context, syncExecutor); this.scripts = new LettuceRedisScriptOperations(scriptRegistry, gateway, context, syncExecutor); - this.pubSub = new LettuceRedisPubSubOperations(pubSubGateway, context, syncExecutor); - this.reactivePubSub = - new LettuceReactiveRedisPubSubOperations(pubSubGateway, context, reactiveExecutor); - } - - Optional shardedPubSub() { - return LettuceRedisShardedPubSubOperations.ifSupported( - capabilities, pubSubGateway, context, syncExecutor); } LettuceRedisBatch.Builder batch() { diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java deleted file mode 100644 index 8e318ada..00000000 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PubSubPattern; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ShardedPubSubChannel; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Subscription; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec.LongCodec; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec.Utf8StringCodec; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** The Pub/Sub contract from design section 10.10. */ -class RedisPubSubOperationsContractTest { - - private final RedisOperationsFixture fixture = new RedisOperationsFixture(); - - private final PubSubChannel orders = - new PubSubChannel<>( - RedisOperationsFixture.NAMESPACE, - new RedisKeyName("orders", "created"), - Utf8StringCodec.instance()); - - @Test - @DisplayName("a subscriber receives what is published and stops when it is closed") - void subscriptionDeliversUntilClosed() { - List received = new ArrayList<>(); - - try (Subscription subscription = - fixture.pubSub.subscribe(List.of(orders), (channel, message) -> received.add(message))) { - assertThat(subscription.active()).isTrue(); - assertThat(subscription.targets()).containsExactly(orders.render()); - assertThat(fixture.pubSub.publish(orders, "one")).isEqualTo(1L); - assertThat(received).containsExactly("one"); - } - - assertThat(fixture.pubSub.publish(orders, "two")).isZero(); - assertThat(received).containsExactly("one"); - assertThat(fixture.pubSubGateway.activeSubscriptions()).isZero(); - } - - @Test - @DisplayName("a channel outside the bound namespace is refused") - void foreignNamespaceIsRefused() { - PubSubChannel foreign = - new PubSubChannel<>( - new RedisNamespace("prod", "billing", "shared"), - new RedisKeyName("orders", "created"), - Utf8StringCodec.instance()); - - assertThatThrownBy(() -> fixture.pubSub.publish(foreign, "one")) - .isInstanceOf(RedisCommandRejectedException.class); - assertThatThrownBy(() -> fixture.pubSub.subscribe(List.of(foreign), (channel, message) -> {})) - .isInstanceOf(RedisCommandRejectedException.class); - } - - @Test - @DisplayName("an empty subscription is refused") - void anEmptySubscriptionIsRefused() { - assertThatThrownBy(() -> fixture.pubSub.subscribe(List.of(), (channel, message) -> {})) - .isInstanceOf(RedisCommandRejectedException.class); - } - - @Test - @DisplayName("each subscribed channel is decoded with its own codec") - void eachChannelUsesItsOwnCodec() { - // The failure this pins down is silent. Subscribing to two channels used to decode every - // message with the first channel's codec, so the second channel's payloads came back - // reinterpreted under the wrong schema whenever the framings happened to be compatible. - PubSubChannel counters = - new PubSubChannel<>( - RedisOperationsFixture.NAMESPACE, - new RedisKeyName("counters", "hits"), - LongCodec.instance()); - List received = new ArrayList<>(); - - try (Subscription subscription = - fixture.pubSub.subscribe(List.of(orders), (channel, message) -> received.add(message))) { - assertThat(subscription.active()).isTrue(); - fixture.pubSub.publish(orders, "text"); - } - - try (Subscription subscription = - fixture.pubSub.subscribe(List.of(counters), (channel, message) -> received.add(message))) { - assertThat(subscription.active()).isTrue(); - fixture.pubSub.publish(counters, 7L); - } - - assertThat(received).containsExactly("text", 7L); - } - - @Test - @DisplayName("a pattern subscription refuses to mix codecs it cannot tell apart") - void patternSubscriptionRefusesMixedCodecs() { - // A matched message carries the concrete channel, never the pattern that matched it, so there - // is no key to resolve a per-pattern codec by. Picking the first one silently decoded the - // other pattern's payloads under the wrong schema. - PubSubPattern text = - new PubSubPattern<>( - RedisOperationsFixture.NAMESPACE, "orders*", Utf8StringCodec.instance()); - PubSubPattern other = - new PubSubPattern<>(RedisOperationsFixture.NAMESPACE, "audit*", ByteTextCodec.INSTANCE); - - assertThatThrownBy( - () -> fixture.pubSub.patternSubscribe(List.of(text, other), (channel, message) -> {})) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("one codec for every pattern"); - } - - /** A second String codec with a different identity, so "same type" cannot mask the mismatch. */ - private enum ByteTextCodec - implements dev.caskeleton.adapter.outbound.cache.redis.sdk.api.codec.RedisCodec { - INSTANCE; - - @Override - public String id() { - return "byte-text"; - } - - @Override - public byte[] encode(String value) { - return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); - } - - @Override - public String decode(byte[] bytes) { - return new String(bytes, java.nio.charset.StandardCharsets.UTF_8); - } - } - - @Test - @DisplayName("a pattern subscription matches inside the namespace") - void patternSubscriptionMatchesInsideTheNamespace() { - PubSubPattern pattern = - new PubSubPattern<>( - RedisOperationsFixture.NAMESPACE, "orders*", Utf8StringCodec.instance()); - List received = new ArrayList<>(); - - try (Subscription subscription = - fixture.pubSub.patternSubscribe( - List.of(pattern), (channel, message) -> received.add(channel + '=' + message))) { - assertThat(subscription.active()).isTrue(); - fixture.pubSub.publish(orders, "one"); - } - - assertThat(received).containsExactly(orders.render() + "=one"); - } - - @Test - @DisplayName("sharded pub/sub is absent below Redis 7.0 and present from 7.0") - void shardedPubSubIsVersionGated() { - RedisOperationsFixture legacy = - new RedisOperationsFixture(RedisVersion.parse("7.2.5"), List.of()); - assertThat(legacy.shardedPubSub()).isEmpty(); - - RedisOperationsFixture modern = - new RedisOperationsFixture( - RedisVersion.parse("7.4.0"), - List.of( - dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapability - .SHARDED_PUBSUB)); - LettuceRedisShardedPubSubOperations sharded = modern.shardedPubSub().orElseThrow(); - - ShardedPubSubChannel channel = - new ShardedPubSubChannel<>( - RedisOperationsFixture.NAMESPACE, - new RedisKeyName("orders", "shard"), - Utf8StringCodec.instance()); - List received = new ArrayList<>(); - - try (Subscription subscription = - sharded.subscribe(List.of(channel), (name, message) -> received.add(message))) { - assertThat(subscription.active()).isTrue(); - assertThat(sharded.publish(channel, "one")).isEqualTo(1L); - } - - assertThat(received).containsExactly("one"); - } - - @Test - @DisplayName("a cancelled reactive subscription releases its connection") - void reactiveSubscriptionReleasesOnCancel() { - List received = new ArrayList<>(); - var disposable = fixture.reactivePubSub.subscribe(List.of(orders)).subscribe(received::add); - - fixture.pubSub.publish(orders, "one"); - assertThat(received).containsExactly("one"); - assertThat(fixture.pubSubGateway.activeSubscriptions()).isEqualTo(1); - - disposable.dispose(); - assertThat(fixture.pubSubGateway.activeSubscriptions()).isZero(); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java index 56060a36..5c66b37b 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java @@ -4,11 +4,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.SetKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.codec.Utf8StringCodec; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.RedisCommandCatalog; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java index 082272f0..45e81a32 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java @@ -3,10 +3,10 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.programmability.RedisArgument; import dev.caskeleton.adapter.outbound.cache.redis.sdk.programmability.RegisteredRedisScript; import java.nio.charset.StandardCharsets; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java index 6c575edd..b791b102 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java @@ -3,16 +3,16 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.TypedRedisKeys; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.ValueKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Expiration; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.RedisSlotCalculator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.SameSlotValidator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java index 977660d6..cd17dfae 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java @@ -3,17 +3,17 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.TypedRedisKeys; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.ValueKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Expiration; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.RedisSlotCalculator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.SameSlotValidator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java index 93a40acd..da3d95ce 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java @@ -3,37 +3,39 @@ package dev.caskeleton.adapter.outbound.cache.redis.sdk.programmability; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.RedisTopologyEndpoint; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.cluster.RedisSlotCalculator; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisCredentialResolver.RedisCredentials; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.config.RedisRuntimeSettings; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccount; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisLane; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisTopologyClientFactory; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisKeyRules; +import dev.caskeleton.adapter.outbound.cache.redis.runtime.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisCapabilities; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisVersion; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCrossSlotException; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.QualifiedRedisKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyName; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRenderer; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisKeyRules; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisSlotTag; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.ValueKey; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.Expiration; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.RedisSlotCalculator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.cluster.SameSlotValidator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPermitVerifier; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.ConfiguredRedisPolicyAuthority; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCredentialResolver.RedisCredentials; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.CommandPolicyGuard; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.LettuceExceptionTranslator; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.QueueingRedisCommandExecutor; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.RedisCommandCatalog; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisCredentialRole; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisTopologyClientFactory; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisSdkLane; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisOperationContext; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisOperationLimits; import java.time.Duration; import java.util.ArrayList; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -76,7 +78,7 @@ class LiveRedisClusterTransactionTest { @BeforeEach void openRuntime() { - RedisSdkSettings settings = new RedisSdkSettings(); + RedisRuntimeSettings settings = new RedisRuntimeSettings(); settings.setEnabled(true); settings.setMode(endpoint.mode()); settings.setNodes(new ArrayList<>(List.of(endpoint.host() + ":" + endpoint.port()))); @@ -84,16 +86,18 @@ class LiveRedisClusterTransactionTest { settings.getNamespace().setService(NAMESPACE.service()); settings.getNamespace().setDomain(NAMESPACE.domain()); - Map accounts = new EnumMap<>(RedisCredentialRole.class); + Map accounts = new LinkedHashMap<>(); accounts.put( - RedisCredentialRole.APPLICATION, + RedisAccount.APPLICATION, new RedisCredentials( endpoint.username(), endpoint.password().isBlank() ? "fixture-application" : endpoint.password())); - Map limits = new EnumMap<>(RedisConnectionKind.class); + Map limits = new LinkedHashMap<>(); for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 4); } + // The transaction lane is the SDK's, composed on the runtime the way a service composes it. + limits.put(RedisSdkLane.TRANSACTION, 4); owner = new RedisRuntimeOwner( new RedisTopologyClientFactory( diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredProductionSecrets.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredProductionSecrets.java new file mode 100644 index 00000000..6572e04c --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredProductionSecrets.java @@ -0,0 +1,24 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import java.util.List; +import org.springframework.core.env.Environment; + +/** + * The production secrets a module needs, given what this deployment selected. + * + *

Contributed as a bean by the module that owns the secrets and read by the composition root's + * secret-source guard, which checks each named secret resolves under the {@code prod} profile. The + * guard does not know which roles a module has or which secret each one needs; before this it + * spelled out every Redis role's selector and secret prefix itself. + */ +@FunctionalInterface +public interface RequiredProductionSecrets { + + /** + * Names the secrets the selected capabilities need. + * + * @param environment the resolved environment + * @return the secret names; empty when nothing the module owns is selected + */ + List requiredSecrets(Environment environment); +} 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 new file mode 100644 index 00000000..19c671e1 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRule.java @@ -0,0 +1,51 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import java.util.List; +import org.springframework.core.env.Environment; + +/** + * One fail-fast startup rule over the resolved environment. + * + *

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

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. + */ +public interface StartupRule { + + /** + * The phase a violation of this rule belongs to, which decides the exit code. + * + * @return the phase + */ + StartupPhase phase(); + + /** + * What the failure message leads with: the thing being validated, not that validation failed. + * + * @return the summary + */ + String summary(); + + /** + * What the operator should do, printed after the violations. + * + * @return the remedy, or {@code null} for none + */ + default String remedy() { + return null; + } + + /** + * Finds every violation in the environment. + * + * @param environment the resolved environment + * @return operator-facing descriptions of what is wrong; empty when nothing is + */ + List violations(Environment environment); +} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java new file mode 100644 index 00000000..372e5645 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleAutoConfiguration.java @@ -0,0 +1,27 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; + +/** + * The one startup-rule runner, arriving with the support module every capability already depends + * on, so a module contributes rules as beans and never a runner of its own. + */ +@AutoConfiguration +public class StartupRuleAutoConfiguration { + + /** + * The runner over every contributed rule. + * + * @param environment the resolved environment + * @param rules the rules modules contributed + * @return the runner + */ + @Bean + public StartupRuleRunner startupRuleRunner( + Environment environment, ObjectProvider rules) { + return new StartupRuleRunner(environment, rules.orderedStream().toList()); + } +} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java new file mode 100644 index 00000000..ec1d8903 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunner.java @@ -0,0 +1,53 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import java.util.List; +import java.util.Objects; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.core.env.Environment; + +/** + * Runs every {@link StartupRule} the context holds, once, after all singletons are instantiated and + * before the context finishes refreshing. + * + *

The one place a rule's violations become a failure: a {@link StartupValidationContext} opened + * for the rule's phase, so the exit code, the {@code error.code} field and the {@code + * startup.phase} log field follow from the rule's declaration. Rules run in bean order and the + * first rule with violations stops the boot, reporting all of that rule's violations at once. + */ +public final class StartupRuleRunner implements SmartInitializingSingleton { + + private final Environment environment; + + private final List rules; + + /** + * Creates the runner. + * + * @param environment the resolved environment + * @param rules every rule the context holds + */ + public StartupRuleRunner(Environment environment, List rules) { + this.environment = Objects.requireNonNull(environment, "environment must be non-null"); + this.rules = List.copyOf(Objects.requireNonNull(rules, "rules must be non-null")); + } + + @Override + public void afterSingletonsInstantiated() { + for (StartupRule rule : rules) { + enforce(rule, environment); + } + } + + /** + * Runs one rule and raises its violations as its phase's typed failure. + * + * @param rule the rule + * @param environment the resolved environment + * @throws StartupFailureException when the rule found a violation + */ + public static void enforce(StartupRule rule, Environment environment) { + StartupValidationContext.forPhase(rule.phase()) + .rejectAll(rule.violations(environment)) + .failIfViolated(rule.summary(), rule.remedy()); + } +} diff --git a/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 4d597e1c..a2cc9af4 100644 --- a/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,2 +1,3 @@ dev.caskeleton.adapter.outbound.support.OutboundSupportConfig dev.caskeleton.adapter.outbound.support.messaging.IntegrationEventEncoderAutoConfiguration +dev.caskeleton.adapter.outbound.support.startup.StartupRuleAutoConfiguration diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java new file mode 100644 index 00000000..1d4567b2 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupRuleRunnerTest.java @@ -0,0 +1,94 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.env.Environment; + +class StartupRuleRunnerTest { + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(StartupRuleAutoConfiguration.class)); + + @Test + @DisplayName("규칙의 위반 전부를 그 규칙 phase의 종료 코드로 한 번에 보고한다") + void aRulesViolationsFailTheBootWithItsPhasesExitCode() { + runner + .withBean( + StartupRule.class, + () -> rule(StartupPhase.PROFILE_CHECK, "prod forbids these", List.of("a=1", "b=2"))) + .run( + context -> + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessage("prod forbids these: a=1; b=2") + .extracting(failure -> ((StartupFailureException) failure).errorCode()) + .isEqualTo(StartupErrorCode.PROFILE_MISMATCH)); + } + + @Test + void aContextWhoseRulesFindNothingStarts() { + runner + .withBean( + StartupRule.class, () -> rule(StartupPhase.ENV_VALIDATION, "nothing wrong", List.of())) + .run(context -> assertThat(context).hasNotFailed()); + } + + @Test + void aRuleReadsTheResolvedEnvironment() { + // given + List seen = new ArrayList<>(); + StartupRule reading = + new StartupRule() { + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; + } + + @Override + public String summary() { + return "reads"; + } + + @Override + public List violations(Environment environment) { + seen.add(environment.getProperty("probe.value")); + return List.of(); + } + }; + + // when + runner + .withPropertyValues("probe.value=resolved") + .withBean(StartupRule.class, () -> reading) + .run(context -> {}); + + // then + assertThat(seen).containsExactly("resolved"); + } + + private static StartupRule rule(StartupPhase phase, String summary, List violations) { + return new StartupRule() { + @Override + public StartupPhase phase() { + return phase; + } + + @Override + public String summary() { + return summary; + } + + @Override + public List violations(Environment environment) { + return violations; + } + }; + } +} diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index b8f96fba..f821acf5 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -82,6 +82,11 @@ configurations, Redis as one 376-line class. error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`, `ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`. +- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations, + and the one `StartupRuleRunner` raises them. A guard that needs another bean stays a bean. A + capability's production secrets are the capability's: its module contributes a + `RequiredProductionSecrets` bean, and `SecretSourceValidator` checks the names without knowing + which roles exist. ## Decomposition threshold diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index a8815dc5..29ffbcc5 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -144,10 +144,21 @@ README의 "startup" 절에 있다. `docs/registries/secrets-classification.yaml`의 secret 행과 정확히 일치해야 하며, `SecretsClassificationRegistryTest`가 1:1 일치를 단언한다. 그래서 레지스트리에 시크릿을 추가/제거하고 이 상수를 갱신하지 않으면 빌드가 깨진다 — drift 를 컴파일·테스트 단계에서 잡는다. +- **capability의 시크릿은 그 모듈이 기여한다.** 선택한 역할에만 필요한 시크릿(Redis 역할별 + 비밀번호·HMAC 등)은 이 상수에 없다. 소유 모듈이 `RequiredProductionSecrets` 빈으로 "지금 선택된 + 역할이 요구하는 시크릿"을 알려 주고(Redis는 `cache-redis`의 `RedisProductionSecrets`), 이 가드는 + 그 이름들이 백엔드에서 풀리는지만 본다. 레지스트리에서는 그 행들이 `required_when`을 가진다. - **prod 판정은 대소문자 무시다.** `SPRING_PROFILES_ACTIVE=PROD` 같은 배포 오타도 prod 가드를 발동시켜야 하므로 `equalsIgnoreCase`로 비교한다(`Environment#matchesProfiles`는 대소문자를 구분해 "PROD"를 통과시킨다). +환경만 읽는 검사(`RuntimeNumericBoundsValidator`, `ErrorDetailExposureSafetyValidator`와 +persistence-jpa의 datasource·Flyway·OSIV·TLS·vendor·Hikari 검사)는 `StartupRule`이다: 위반 목록만 +돌려주고, `adapter:outbound:support`의 `StartupRuleRunner` 하나가 모든 싱글톤 생성 후 규칙마다 그 +phase의 종료 코드로 실패시킨다. 다른 bean이 필요한 검사(`SecretSourceValidator`의 `SecretSourcePort`, +`StartupSafetyValidator`의 bean factory, persistence-jpa의 datasource 검사)는 계속 bean이고, 부팅 전에 +돌아야 하는 profile 규칙(`RuntimeEnvironmentProfileValidator`)은 `EnvironmentPostProcessor`로 남는다. + 관계형 설정 가드(`HikariPoolConstraintValidator`, `OpenInViewSafetyValidator`, `JpaDangerousConfigurationGuard`, `PostgreSqlTransportSecurityValidator`, `PersistenceVendorProdSafetyValidator`)는 `adapter:outbound:persistence-jpa`로 옮겼다. 풀 크기 diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java index 93126679..5407b65f 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java @@ -1,13 +1,13 @@ 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.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupRule; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; /** @@ -16,7 +16,7 @@ import org.springframework.core.env.Environment; * each is an environment override away in {@code application.yml}, so a YAML default alone does not * hold them off in prod. */ -public class ErrorDetailExposureSafetyValidator implements SmartInitializingSingleton { +public class ErrorDetailExposureSafetyValidator implements StartupRule { /** Each key that must stay {@code never}, with the name an operator would have set. */ private static final Map MUST_BE_NEVER = new LinkedHashMap<>(); @@ -30,16 +30,21 @@ public class ErrorDetailExposureSafetyValidator implements SmartInitializingSing private static final String INCLUDE_EXCEPTION = "spring.web.error.include-exception"; - private final Environment environment; - - public ErrorDetailExposureSafetyValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.PROFILE_CHECK; } @Override - public void afterSingletonsInstantiated() { + public String summary() { + return "prod profile requires error details to stay out of responses (include-* = never, " + + "include-exception = false), but found"; + } + + @Override + public List violations(Environment environment) { if (!RuntimeProfileSnapshot.from(environment).isProduction()) { - return; + return List.of(); } List violations = new ArrayList<>(); MUST_BE_NEVER.forEach( @@ -53,12 +58,7 @@ public class ErrorDetailExposureSafetyValidator implements SmartInitializingSing if (includeException != null && "true".equals(normalized(includeException))) { violations.add(INCLUDE_EXCEPTION + "=true"); } - if (!violations.isEmpty()) { - throw StartupFailures.profileMismatch( - "prod profile requires error details to stay out of responses (include-* = never, " - + "include-exception = false), but found " - + String.join(", ", violations)); - } + return violations; } private static String normalized(String value) { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java index 8b3dd6bc..e2517bec 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java @@ -1,16 +1,16 @@ 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 java.util.ArrayList; import java.util.List; -import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; /** * Fail-fast startup guard for the high-risk numeric runtime knobs (pool/thread sizing). Reads the * resolved Spring property; an absent key is skipped. See README for the design rationale. */ -public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton { +public class RuntimeNumericBoundsValidator implements StartupRule { /** A numeric property bound: resolved Spring key, the {@code APP_*} env key, and minimum. */ record Bound(String springKey, String envKey, int minInclusive) {} @@ -25,23 +25,27 @@ public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton new Bound("server.tomcat.threads.min-spare", "APP_SERVER_TOMCAT_MIN_SPARE_THREADS", 0), new Bound("server.tomcat.accept-count", "APP_SERVER_TOMCAT_ACCEPT_COUNT", 0)); - private final Environment environment; - - public RuntimeNumericBoundsValidator(Environment environment) { - this.environment = environment; + @Override + public StartupPhase phase() { + return StartupPhase.ENV_VALIDATION; } @Override - public void afterSingletonsInstantiated() { - StartupValidationContext violations = - StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION); + public String summary() { + return "invalid runtime numeric configuration (feature-env-driven-runtime-configuration " + + "D10 — no lenient default)"; + } + + @Override + public List violations(Environment environment) { + List violations = new ArrayList<>(); for (Bound bound : BOUNDS) { Integer value = environment.getProperty(bound.springKey(), Integer.class); if (value == null) { continue; // absent → skip (framework default owns it) } if (value < bound.minInclusive()) { - violations.reject( + violations.add( bound.envKey() + " (" + bound.springKey() @@ -51,8 +55,6 @@ public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton + value); } } - violations.failIfViolated( - "invalid runtime numeric configuration (feature-env-driven-runtime-configuration " - + "D10 — no lenient default)"); + return violations; } } 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 f8cac611..bf99b5dc 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 @@ -4,7 +4,6 @@ import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; /** * Wires the runtime-safety startup fail-fast validators into the running application. See README @@ -21,12 +20,12 @@ public class RuntimeSafetyConfig { } @Bean - RuntimeNumericBoundsValidator runtimeNumericBoundsValidator(Environment environment) { - return new RuntimeNumericBoundsValidator(environment); + RuntimeNumericBoundsValidator runtimeNumericBoundsValidator() { + return new RuntimeNumericBoundsValidator(); } @Bean - ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) { - return new ErrorDetailExposureSafetyValidator(environment); + 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 ddde9f4a..1849aec9 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java @@ -1,6 +1,8 @@ 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; @@ -22,7 +24,10 @@ public class SecretSourceConfig { @Bean SecretSourceValidator secretSourceValidator( - ConfigurableEnvironment environment, SecretSourcePort secretSource) { - return new SecretSourceValidator(environment, secretSource); + ConfigurableEnvironment environment, + SecretSourcePort secretSource, + ObjectProvider contributed) { + return new SecretSourceValidator( + environment, secretSource, contributed.orderedStream().toList()); } } 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 61cc9cb3..b8db585a 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 @@ -1,6 +1,7 @@ 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.application.outbound.SecretSourcePort; @@ -22,31 +23,14 @@ public class SecretSourceValidator implements SmartInitializingSingleton { static final String LOCAL_DEV_SENTINEL_PREFIX = "__LOCAL_DEV_"; /** - * The one global Redis switch, bound from {@code APP_REDIS_ENABLED}. - * - *

There is deliberately no second capability switch. {@code APP_CACHE_REDIS_ENABLED} used to - * read like one, which is how a deployment with no Redis at all still had to supply cache Redis - * credentials to reach a running state. - */ - public static final String REDIS_ENABLED_PROPERTY = "app.redis.enabled"; - - /** - * Secret keys that must be injected under the {@code prod} profile. {@code - * SecretsClassificationRegistryTest} asserts this list matches the registry 1:1. See README for - * the design rationale. + * Secret keys that must be injected under the {@code prod} profile whatever the deployment + * selected. {@code SecretsClassificationRegistryTest} asserts this list matches the registry 1:1. + * A capability's own secrets are not listed here: the module that owns them contributes them + * ({@link RequiredProductionSecrets}) for the roles the deployment selected, and the registry + * marks them {@code required_when}. See README for the design rationale. */ public static final List REQUIRED_PROD_SECRETS = - List.of( - "APP_DATASOURCE_PASSWORD", - "APP_CACHE_REDIS_PASSWORD", - "APP_CACHE_REDIS_KEY_HMAC_SECRET", - "APP_RATE_LIMIT_REDIS_PASSWORD", - "APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET", - "APP_SESSION_REDIS_PASSWORD", - "APP_SESSION_REDIS_KEY_HMAC_SECRET", - "APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET", - "APP_LEASE_REDIS_KEY_HMAC_SECRET", - "APP_PRIVACY_PSEUDONYMIZATION_SALT"); + List.of("APP_DATASOURCE_PASSWORD", "APP_PRIVACY_PSEUDONYMIZATION_SALT"); /** * The relational credential, required only while relational persistence is on. The switch is set @@ -61,10 +45,15 @@ public class SecretSourceValidator implements SmartInitializingSingleton { private final ConfigurableEnvironment environment; private final SecretSourcePort secretSource; + private final List contributed; - public SecretSourceValidator(ConfigurableEnvironment environment, SecretSourcePort secretSource) { + public SecretSourceValidator( + ConfigurableEnvironment environment, + SecretSourcePort secretSource, + List contributed) { this.environment = environment; this.secretSource = secretSource; + this.contributed = List.copyOf(contributed); } @Override @@ -102,76 +91,23 @@ public class SecretSourceValidator implements SmartInitializingSingleton { } private void collectMissingSecretViolations(StartupValidationContext validation) { + Set required = new LinkedHashSet<>(); for (String key : REQUIRED_PROD_SECRETS) { - if (isRedisMaterial(key) && !isRedisRoleSelected(key)) { - continue; - } if (DATASOURCE_PASSWORD.equals(key) && !isRelationalPersistenceOn()) { continue; } + required.add(key); + } + // 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))); + for (String key : required) { if (secretSource.resolve(key).isEmpty()) { validation.reject(key + " is missing/blank"); } } } - /** - * Reports whether a required secret is Redis material. - * - *

The prefix is the role, and every role is spelled {@code APP__REDIS_...}. Matching on - * the shared infix rather than enumerating roles means a role added later cannot quietly become - * an unconditional production requirement the way the cache role did. - */ - private static boolean isRedisMaterial(String key) { - return key.contains("_REDIS_"); - } - - /** - * Reports whether the deployment actually selected the Redis role this secret belongs to. - * - *

Two conditions, and both must hold. {@code app.redis.enabled} is the single global switch: - * with Redis off nothing Redis-shaped is created, so demanding its credentials would fail a - * deployment over an adapter it never asked for. On top of that the specific role has to be - * bound, because a deployment that runs Redis for its cache owes nothing to the session store. - */ - private boolean isRedisRoleSelected(String key) { - if (!isRedisGloballyEnabled()) { - return false; - } - if (key.startsWith("APP_CACHE_REDIS_")) { - return isRedisCacheBound(); - } - if (key.startsWith("APP_RATE_LIMIT_REDIS_")) { - return isSelected("ca-skeleton.capabilities.rate-limit.provider", "disabled", "redis"); - } - if (key.startsWith("APP_SESSION_REDIS_")) { - return isSelected("ca-skeleton.security.auth-mode", "jwt", "redis-session"); - } - if (key.startsWith("APP_IDEMPOTENCY_REDIS_")) { - return isSelected("ca-skeleton.capabilities.idempotency.provider", "disabled", "redis"); - } - if (key.startsWith("APP_LEASE_REDIS_")) { - return isSelected("ca-skeleton.capabilities.lease.provider", "disabled", "redis"); - } - // An unrecognised Redis role is required whenever Redis is on: an unknown role must fail - // closed, not silently exempt itself from the production secret contract. - return true; - } - - private boolean isRedisGloballyEnabled() { - return Boolean.parseBoolean(environment.getProperty(REDIS_ENABLED_PROPERTY, "false")); - } - - private boolean isRedisCacheBound() { - return "redis" - .equalsIgnoreCase( - environment.getProperty("ca-skeleton.capabilities.cache.bindings.default", "disabled")); - } - - private boolean isSelected(String property, String fallback, String selecting) { - return selecting.equalsIgnoreCase(environment.getProperty(property, fallback)); - } - private boolean isRelationalPersistenceOn() { return Boolean.parseBoolean( environment.getProperty(RELATIONAL_PERSISTENCE_PROPERTY, "false").trim()); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java index 91203bfe..8b347bbe 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java @@ -4,6 +4,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.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -15,7 +16,8 @@ import org.springframework.core.env.Environment; class ErrorDetailExposureSafetyValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @ParameterizedTest @CsvSource({ @@ -67,7 +69,7 @@ class ErrorDetailExposureSafetyValidatorTest { @Bean ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) { - return new ErrorDetailExposureSafetyValidator(environment); + return new ErrorDetailExposureSafetyValidator(); } } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java index 0b82be3b..0d594af4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java @@ -4,6 +4,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.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -19,7 +20,8 @@ import org.springframework.core.env.Environment; class RuntimeNumericBoundsValidatorTest { private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + new ApplicationContextRunner() + .withUserConfiguration(StartupRuleAutoConfiguration.class, ValidatorConfig.class); @Test void nonPositiveMaxThreadsFailsStartupNamingTheAppKey() { @@ -77,7 +79,7 @@ class RuntimeNumericBoundsValidatorTest { static class ValidatorConfig { @Bean RuntimeNumericBoundsValidator runtimeNumericBoundsValidator(Environment environment) { - return new RuntimeNumericBoundsValidator(environment); + return new RuntimeNumericBoundsValidator(); } } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java index 5b806aa8..c3fcd230 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java @@ -2,10 +2,14 @@ package dev.caskeleton.bootstrap.runtime; 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 java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,12 +30,7 @@ class SecretSourceValidatorTest { /** All required prod secrets set to real (non-sentinel) values. */ private static String[] allRequiredSecretsPresent() { return new String[] { - "APP_DATASOURCE_PASSWORD=real-db-password", - "APP_CACHE_REDIS_PASSWORD=real-redis-password", - "APP_CACHE_REDIS_KEY_HMAC_SECRET=real-redis-key-hmac-secret", - "APP_RATE_LIMIT_REDIS_PASSWORD=real-rate-limit-redis-password", - "APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET=real-rate-limit-redis-key-hmac-secret", - "APP_PRIVACY_PSEUDONYMIZATION_SALT=real-salt" + "APP_DATASOURCE_PASSWORD=real-db-password", "APP_PRIVACY_PSEUDONYMIZATION_SALT=real-salt" }; } @@ -152,71 +151,6 @@ class SecretSourceValidatorTest { .run(context -> assertThat(context).hasNotFailed()); } - // ---- Redis is optional: no switch, no secret requirement ----------------- - - @Test - void prodProfileWithoutRedisDoesNotRequireAnyRedisSecret() { - String[] nonRedisSecrets = - Arrays.stream(allRequiredSecretsPresent()) - .filter(value -> !value.contains("_REDIS_")) - .toArray(String[]::new); - - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(nonRedisSecrets) - .run(context -> assertThat(context).hasNotFailed()); - } - - @Test - void prodProfileWithRedisExplicitlyDisabledDoesNotRequireAnyRedisSecret() { - String[] nonRedisSecrets = - Arrays.stream(allRequiredSecretsPresent()) - .filter(value -> !value.contains("_REDIS_")) - .toArray(String[]::new); - - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(nonRedisSecrets) - .withPropertyValues("app.redis.enabled=false") - .run(context -> assertThat(context).hasNotFailed()); - } - - @Test - void enabledRedisCacheRequiresItsOwnMaterialInProd() { - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(allRequiredSecretsPresent()) - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.capabilities.cache.bindings.default=redis", - "APP_CACHE_REDIS_KEY_HMAC_SECRET=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> - assertThat(e.errorCode()) - .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasStackTraceContaining("APP_CACHE_REDIS_KEY_HMAC_SECRET"); - }); - } - - @Test - void redisEnabledWithoutAnyRoleBoundStillRequiresNoRoleSecret() { - String[] nonRedisSecrets = - Arrays.stream(allRequiredSecretsPresent()) - .filter(value -> !value.contains("_REDIS_")) - .toArray(String[]::new); - - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(nonRedisSecrets) - .withPropertyValues("app.redis.enabled=true") - .run(context -> assertThat(context).hasNotFailed()); - } - @Test void nonProdProfileWithMissingRequiredSecretsIsAllowed() { runner @@ -224,130 +158,51 @@ class SecretSourceValidatorTest { .run(context -> assertThat(context).hasNotFailed()); } + // ---- secrets a module contributes for what the deployment selected ------------------------- + @Test - void enabledRateLimitRedisRequiresItsDedicatedSecretsInProd() { + @DisplayName("모듈이 기여한 secret이 prod에서 비어 있으면 기동이 실패한다") + void aSecretAModuleContributedIsRequiredInProd() { runner .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) .withPropertyValues(allRequiredSecretsPresent()) - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.capabilities.rate-limit.provider=redis", - "APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET=") + .withBean(RequiredProductionSecrets.class, () -> environment -> List.of("APP_MODULE_KEY")) .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> - assertThat(e.errorCode()) - .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasStackTraceContaining("APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET"); - }); + context -> + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupFailureException.class) + .hasMessageContaining("APP_MODULE_KEY is missing/blank")); } @Test - void disabledRateLimitRedisDoesNotRequireItsDedicatedSecretsInProd() { - String[] baselineSecrets = - Arrays.stream(allRequiredSecretsPresent()) - .filter(value -> !value.startsWith("APP_RATE_LIMIT_REDIS_")) - .toArray(String[]::new); - + void aSecretAModuleContributedAndSuppliedStartsCleanly() { runner .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(baselineSecrets) - .withPropertyValues("ca-skeleton.capabilities.rate-limit.provider=disabled") + .withPropertyValues(allRequiredSecretsPresent()) + .withPropertyValues("APP_MODULE_KEY=real-module-key") + .withBean(RequiredProductionSecrets.class, () -> environment -> List.of("APP_MODULE_KEY")) .run(context -> assertThat(context).hasNotFailed()); } @Test - void transportEnableAloneDoesNotRequireRedisProviderSecretsInProd() { - String[] baselineSecrets = - Arrays.stream(allRequiredSecretsPresent()) - .filter(value -> !value.startsWith("APP_RATE_LIMIT_REDIS_")) - .toArray(String[]::new); - + void aSecretAModuleContributedIsNotRequiredOutsideProd() { runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(baselineSecrets) - .withPropertyValues("app.rate-limit.enabled=true") + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("local")) + .withBean(RequiredProductionSecrets.class, () -> environment -> List.of("APP_MODULE_KEY")) .run(context -> assertThat(context).hasNotFailed()); } - @Test - void selectedRedisIdempotencyRequiresItsHmacMaterialInProd() { - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(allRequiredSecretsPresent()) - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.capabilities.idempotency.provider=redis", - "APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> - assertThat(e.errorCode()) - .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasStackTraceContaining("APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET"); - }); - } - - @Test - void selectedRedisEfficiencyLeaseRequiresItsHmacMaterialInProd() { - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(allRequiredSecretsPresent()) - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.capabilities.lease.provider=redis", - "APP_LEASE_REDIS_KEY_HMAC_SECRET=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> - assertThat(e.errorCode()) - .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasStackTraceContaining("APP_LEASE_REDIS_KEY_HMAC_SECRET"); - }); - } - - @Test - void redisSessionModeRequiresItsHmacMaterialInProd() { - runner - .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) - .withPropertyValues(allRequiredSecretsPresent()) - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.security.auth-mode=redis-session", - "APP_SESSION_REDIS_PASSWORD=real-session-password", - "APP_SESSION_REDIS_KEY_HMAC_SECRET=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOfSatisfying( - StartupFailureException.class, - e -> - assertThat(e.errorCode()) - .isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED)) - .hasStackTraceContaining("APP_SESSION_REDIS_KEY_HMAC_SECRET"); - }); - } - @Configuration static class ValidatorConfig { @Bean - SecretSourceValidator secretSourceValidator(ConfigurableEnvironment environment) { + 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)); + environment, + SecretSourceFactory.create(SecretSourceStrategy.ENVIRONMENT, environment), + contributed.orderedStream().toList()); } } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLeaseContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLeaseContractTest.java new file mode 100644 index 00000000..b916060b --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLeaseContractTest.java @@ -0,0 +1,21 @@ +package dev.caskeleton.application.lease.testkit; + +import dev.caskeleton.application.lease.DistributedLeasePort; +import java.time.Duration; + +/** The fake answers to the same ownership contract as the Redis adapter. */ +class InMemoryDistributedLeaseContractTest extends DistributedLeaseContract { + + private InMemoryDistributedLease lease; + + @Override + protected DistributedLeasePort newPort() { + lease = new InMemoryDistributedLease(); + return lease; + } + + @Override + protected void elapse(Duration duration) { + lease.advance(duration); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/DistributedLeaseContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/DistributedLeaseContract.java new file mode 100644 index 00000000..7ed64158 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/DistributedLeaseContract.java @@ -0,0 +1,188 @@ +package dev.caskeleton.application.lease.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.lease.DistributedLeasePort; +import dev.caskeleton.application.lease.LeaseAcquireOutcome; +import dev.caskeleton.application.lease.LeaseAttempt; +import dev.caskeleton.application.lease.LeaseHandle; +import dev.caskeleton.application.lease.LeaseInspectionOutcome; +import dev.caskeleton.application.lease.LeaseInspectionRequest; +import dev.caskeleton.application.lease.LeaseReleaseOutcome; +import dev.caskeleton.application.lease.LeaseRenewOutcome; +import dev.caskeleton.application.lease.LeaseRequest; +import java.time.Duration; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DistributedLeasePort} promises about ownership, run against the in-memory fake + * and the Redis adapter alike. + * + *

The lease is an efficiency lease — it carries no fencing token for the resource it guards, and + * a paused holder cannot be stopped from acting. What it does promise is the fencing rule for its + * own record: a terminal write names its owner, and the write of a holder that has been displaced + * matches nothing. A holder whose lease expired and was taken by somebody else must not be able to + * renew or release the successor's lease, and must be told it no longer owns it. + * + *

Each test works on a fresh resource digest, so a shared live server needs no cleanup. + */ +public abstract class DistributedLeaseContract { + + private static final String PURPOSE = "contract"; + + private DistributedLeasePort port; + + private String resource; + + /** + * Returns the port under test, fresh or shared. + * + * @return the port + */ + protected abstract DistributedLeasePort newPort(); + + /** + * Lets time pass for the port: longer than {@link #leaseTtl()}, so a lease taken now expires. + * + * @param duration how long + */ + protected abstract void elapse(Duration duration); + + /** + * The lease TTL the tests acquire with. A live server waits for real, so keep it short there. + * + * @return the TTL + */ + protected Duration leaseTtl() { + return Duration.ofSeconds(30); + } + + @BeforeEach + void freshResource() { + port = newPort(); + // 64 lowercase hex characters from two random UUIDs: a resource no other test touches. + resource = "hv1:" + hex(UUID.randomUUID()) + hex(UUID.randomUUID()); + } + + @Test + void aHeldLeaseIsContendedForAnotherOwner() { + // given + acquire(port.newAttempt("operation-first-holder")); + + // when + LeaseAcquireOutcome second = port.tryAcquire(request(port.newAttempt("operation-second"))); + + // then + assertThat(second).isInstanceOf(LeaseAcquireOutcome.Contended.class); + } + + @Test + @DisplayName("같은 attempt로 다시 acquire하면 경합이 아니라 재생(replay)이다") + void aRetriedAcquireWithTheSameAttemptIsAReplay() { + // given + LeaseAttempt attempt = port.newAttempt("operation-retried-acquire"); + acquire(attempt); + + // when + LeaseAcquireOutcome retried = port.tryAcquire(request(attempt)); + + // then + assertThat(retried).isInstanceOf(LeaseAcquireOutcome.ReplayedSameOperation.class); + } + + @Test + void aDisplacedHoldersRenewIsNotOwner() { + // given + LeaseHandle stale = displacedHolder(); + + // when + LeaseRenewOutcome renewed = stale.renew(leaseTtl()); + + // then + assertThat(renewed).isInstanceOf(LeaseRenewOutcome.NotOwner.class); + } + + @Test + void aDisplacedHoldersRenewLeavesTheSuccessorHoldingTheLease() { + // given + LeaseAttempt successor = port.newAttempt("operation-successor-renew"); + LeaseHandle stale = displacedHolder(successor); + + // when + stale.renew(leaseTtl()); + + // then + assertThat(port.inspect(new LeaseInspectionRequest(PURPOSE, resource, successor))) + .isInstanceOf(LeaseInspectionOutcome.Owned.class); + } + + @Test + void aDisplacedHoldersReleaseIsNotOwner() { + // given + LeaseHandle stale = displacedHolder(); + + // when + LeaseReleaseOutcome released = stale.release(); + + // then + assertThat(released).isInstanceOf(LeaseReleaseOutcome.NotOwner.class); + } + + @Test + void aDisplacedHoldersReleaseLeavesTheSuccessorHoldingTheLease() { + // given + LeaseAttempt successor = port.newAttempt("operation-successor-release"); + LeaseHandle stale = displacedHolder(successor); + + // when + stale.release(); + + // then + assertThat(port.inspect(new LeaseInspectionRequest(PURPOSE, resource, successor))) + .isInstanceOf(LeaseInspectionOutcome.Owned.class); + } + + @Test + void aReleasedLeaseReleasedAgainIsAlreadyAbsent() { + // given + LeaseHandle handle = acquire(port.newAttempt("operation-released-twice")); + handle.release(); + + // when + LeaseReleaseOutcome again = handle.release(); + + // then + assertThat(again).isInstanceOf(LeaseReleaseOutcome.AlreadyAbsent.class); + } + + private static String hex(UUID uuid) { + return uuid.toString().replace("-", ""); + } + + private LeaseHandle displacedHolder() { + return displacedHolder(port.newAttempt("operation-successor")); + } + + /** A holder whose lease expired and was then taken by {@code successor}. */ + private LeaseHandle displacedHolder(LeaseAttempt successor) { + LeaseHandle first = acquire(port.newAttempt("operation-displaced-holder")); + elapse(leaseTtl().plus(leaseTtl().dividedBy(2))); + acquire(successor); + return first; + } + + private LeaseHandle acquire(LeaseAttempt attempt) { + LeaseAcquireOutcome outcome = port.tryAcquire(request(attempt)); + assertThat(outcome) + .as("precondition: the lease is free") + .isInstanceOf(LeaseAcquireOutcome.Acquired.class); + return ((LeaseAcquireOutcome.Acquired) outcome).handle(); + } + + private LeaseRequest request(LeaseAttempt attempt) { + return new LeaseRequest(PURPOSE, resource, Duration.ZERO, leaseTtl(), attempt); + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLease.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLease.java new file mode 100644 index 00000000..2e00ee67 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/lease/testkit/InMemoryDistributedLease.java @@ -0,0 +1,202 @@ +package dev.caskeleton.application.lease.testkit; + +import dev.caskeleton.application.lease.DistributedLeasePort; +import dev.caskeleton.application.lease.LeaseAcquireOutcome; +import dev.caskeleton.application.lease.LeaseAttempt; +import dev.caskeleton.application.lease.LeaseHandle; +import dev.caskeleton.application.lease.LeaseInspectionOutcome; +import dev.caskeleton.application.lease.LeaseInspectionRequest; +import dev.caskeleton.application.lease.LeaseReleaseOutcome; +import dev.caskeleton.application.lease.LeaseRenewOutcome; +import dev.caskeleton.application.lease.LeaseRequest; +import dev.caskeleton.application.lease.LeaseState; +import java.security.SecureRandom; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * The in-memory {@link DistributedLeasePort}: the one fake of the port, held to the same {@link + * DistributedLeaseContract} as the Redis adapter. + * + *

Time moves only through {@link #advance(Duration)}, so an expiry is a statement in the test + * rather than a race with the wall clock. Ownership is {@code ownerToken:operationId}, compared on + * every renew and release — the property the contract exists to hold. + */ +public final class InMemoryDistributedLease implements DistributedLeasePort { + + private static final SecureRandom RANDOM = new SecureRandom(); + + private static final Duration CONTENTION_RETRY_AFTER = Duration.ofMillis(50); + + private final Map leases = new HashMap<>(); + + private long nowMillis; + + /** + * Moves the fake's clock forward. + * + * @param duration how far + */ + public synchronized void advance(Duration duration) { + nowMillis += duration.toMillis(); + } + + @Override + public LeaseAttempt newAttempt(String operationId) { + byte[] entropy = new byte[24]; + RANDOM.nextBytes(entropy); + return new LeaseAttempt( + Base64.getUrlEncoder().withoutPadding().encodeToString(entropy), operationId); + } + + @Override + public synchronized LeaseAcquireOutcome tryAcquire(LeaseRequest request) { + Objects.requireNonNull(request, "request must be non-null"); + String key = key(request.purpose(), request.resourceDigest()); + String ownership = ownershipOf(request.attempt()); + Holding existing = live(key); + if (existing == null) { + leases.put(key, new Holding(ownership, nowMillis + request.leaseTtl().toMillis())); + return new LeaseAcquireOutcome.Acquired( + new Handle(key, request.attempt(), request.leaseTtl())); + } + if (existing.ownership().equals(ownership)) { + return new LeaseAcquireOutcome.ReplayedSameOperation( + new Handle(key, request.attempt(), Duration.ofMillis(existing.expiresAt() - nowMillis))); + } + if (existing.ownership().startsWith(request.attempt().ownerToken() + ":")) { + return new LeaseAcquireOutcome.OwnerOperationConflict(); + } + long remaining = existing.expiresAt() - nowMillis; + return new LeaseAcquireOutcome.Contended( + remaining > 0 ? Duration.ofMillis(remaining) : CONTENTION_RETRY_AFTER); + } + + @Override + public synchronized LeaseInspectionOutcome inspect(LeaseInspectionRequest request) { + Objects.requireNonNull(request, "request must be non-null"); + String key = key(request.purpose(), request.resourceDigest()); + Holding existing = live(key); + if (existing == null) { + return new LeaseInspectionOutcome.Absent(); + } + if (existing.ownership().equals(ownershipOf(request.attempt()))) { + return new LeaseInspectionOutcome.Owned( + new Handle(key, request.attempt(), Duration.ofMillis(existing.expiresAt() - nowMillis))); + } + return existing.ownership().startsWith(request.attempt().ownerToken() + ":") + ? new LeaseInspectionOutcome.OwnerOperationConflict() + : new LeaseInspectionOutcome.NotOwner(); + } + + private Holding live(String key) { + Holding holding = leases.get(key); + if (holding != null && holding.expiresAt() <= nowMillis) { + leases.remove(key); + return null; + } + return holding; + } + + private static String key(String purpose, String resourceDigest) { + return purpose + "|" + resourceDigest; + } + + private static String ownershipOf(LeaseAttempt attempt) { + return attempt.ownerToken() + ":" + attempt.operationId(); + } + + private record Holding(String ownership, long expiresAt) {} + + private final class Handle implements LeaseHandle { + + private final String key; + private final LeaseAttempt attempt; + private final Instant acquiredAt; + private long grantedAtMillis; + private Duration granted; + private LeaseState state = LeaseState.ACTIVE; + + private Handle(String key, LeaseAttempt attempt, Duration granted) { + this.key = key; + this.attempt = attempt; + this.granted = granted; + this.grantedAtMillis = nowMillis; + this.acquiredAt = Instant.ofEpochMilli(nowMillis); + } + + @Override + public String ownerToken() { + return attempt.ownerToken(); + } + + @Override + public String operationId() { + return attempt.operationId(); + } + + @Override + public Instant acquiredAt() { + return acquiredAt; + } + + @Override + public Duration remainingValidity() { + synchronized (InMemoryDistributedLease.this) { + Duration remaining = granted.minusMillis(nowMillis - grantedAtMillis); + return remaining.isNegative() ? Duration.ZERO : remaining; + } + } + + @Override + public Instant observedServerExpiry() { + return acquiredAt.plus(granted); + } + + @Override + public LeaseState state() { + return state == LeaseState.ACTIVE && remainingValidity().isZero() ? LeaseState.LOST : state; + } + + @Override + public LeaseRenewOutcome renew(Duration leaseTtl) { + synchronized (InMemoryDistributedLease.this) { + Holding existing = live(key); + if (existing == null) { + state = LeaseState.LOST; + return new LeaseRenewOutcome.Absent(); + } + if (!existing.ownership().equals(ownershipOf(attempt))) { + state = LeaseState.LOST; + return new LeaseRenewOutcome.NotOwner(); + } + leases.put(key, new Holding(existing.ownership(), nowMillis + leaseTtl.toMillis())); + granted = leaseTtl; + grantedAtMillis = nowMillis; + return new LeaseRenewOutcome.Renewed(leaseTtl); + } + } + + @Override + public LeaseReleaseOutcome release() { + synchronized (InMemoryDistributedLease.this) { + Holding existing = live(key); + if (existing == null) { + state = LeaseState.RELEASED; + return new LeaseReleaseOutcome.AlreadyAbsent(); + } + if (!existing.ownership().equals(ownershipOf(attempt))) { + state = LeaseState.LOST; + return new LeaseReleaseOutcome.NotOwner(); + } + leases.remove(key); + state = LeaseState.RELEASED; + return new LeaseReleaseOutcome.Released(); + } + } + } +} diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index 3da4fec4..47ea2e75 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -20,9 +20,10 @@ persistence·outbound)이 프레임워크 충돌 없이 이 타입들을 공유 경계다. Business quota나 entitlement policy를 담는 application use case가 아니며, 이미 pseudonymized된 subject digest와 bounded policy ID/cost/deadline만 받는다. -`RateLimitPolicy`는 fixed window, sliding-window counter, token bucket 중 하나의 exact parameter -subtype을 고정하고 Lua의 `2^53-1` 안전 정수, 1일 window/refill/cleanup, 1시간 clock regression, -`FAIL_CLOSED`만 허용한다. 결과는 evaluated, known pre-send unavailable, post-dispatch +`RateParameters`는 fixed window, sliding-window counter, token bucket의 exact parameter와 Lua의 +`2^53-1` 안전 정수, 1일 window/refill 한도를 고정한다. 정책 자체(`RateLimitPolicy`, 알고리즘· +실패 정책·evaluation dedup)는 그것을 쓰는 유일한 곳인 `adapter:outbound:cache-redis`의 설정이라 +그 leaf에 있다. 결과는 evaluated, known pre-send unavailable, post-dispatch indeterminate, schema/program/reply incompatible로 분리하므로 adapter가 장애를 allow나 평범한 deny로 숨길 수 없다. 이 패키지는 Java 표준 라이브러리만 사용하며 Redis key, command, Lua, Spring/Lettuce 타입을 노출하지 않는다. diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java index c636455c..680e5fae 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/ratelimit/RateLimitBounds.java @@ -7,8 +7,6 @@ import java.util.regex.Pattern; final class RateLimitBounds { static final Duration MAXIMUM_WINDOW = Duration.ofDays(1); - static final Duration MAXIMUM_CLEANUP_GRACE = Duration.ofDays(1); - static final Duration MAXIMUM_CLOCK_REGRESSION = Duration.ofHours(1); static final Duration MAXIMUM_RETRY_AFTER = Duration.ofMillis(RateParameters.MAXIMUM_EXACT_INTEGER); diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/EdgeRateLimitProviderNeutralContractTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/EdgeRateLimitProviderNeutralContractTest.java index 5001dce4..d26ef890 100644 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/EdgeRateLimitProviderNeutralContractTest.java +++ b/src/shared-contract/src/test/java/dev/caskeleton/shared/ratelimit/EdgeRateLimitProviderNeutralContractTest.java @@ -3,39 +3,11 @@ package dev.caskeleton.shared.ratelimit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.time.Duration; import java.time.Instant; -import java.util.List; import org.junit.jupiter.api.Test; class EdgeRateLimitProviderNeutralContractTest { - @Test - void allPortableAlgorithmsHaveBoundedProviderNeutralPolicies() { - List policies = - List.of( - policy( - RateLimitAlgorithm.FIXED_WINDOW, - new RateParameters.FixedWindow(100, Duration.ofMinutes(1))), - policy( - RateLimitAlgorithm.SLIDING_COUNTER, - new RateParameters.SlidingCounter(100, Duration.ofMinutes(1))), - policy( - RateLimitAlgorithm.TOKEN_BUCKET, - new RateParameters.TokenBucket(100, 10, Duration.ofSeconds(1)))); - - assertThat(policies) - .extracting(RateLimitPolicy::algorithm) - .containsExactlyElementsOf(List.of(RateLimitAlgorithm.values())); - assertThat(policies) - .allSatisfy( - policy -> { - assertThat(policy.failurePolicy()).isEqualTo(RateLimitFailurePolicy.FAIL_CLOSED); - assertThat(policy.evaluationDedupPolicy().maximumEntries()) - .isLessThanOrEqualTo(RateLimitEvaluationDedupPolicy.MAXIMUM_ENTRIES); - }); - } - @Test void requestAcceptsOnlyPseudonymousSubjectAndBoundedEvaluationIdentity() { RateLimitSubjectDigest digest = new RateLimitSubjectDigest("v1:" + "a".repeat(64)); @@ -59,17 +31,4 @@ class EdgeRateLimitProviderNeutralContractTest { Instant.parse("2026-07-29T00:00:01Z"))) .isInstanceOf(IllegalArgumentException.class); } - - private static RateLimitPolicy policy(RateLimitAlgorithm algorithm, RateParameters parameters) { - return new RateLimitPolicy( - "edge-default", - "policy-v1", - algorithm, - parameters, - 10, - Duration.ofSeconds(5), - Duration.ofSeconds(1), - RateLimitFailurePolicy.FAIL_CLOSED, - RateLimitEvaluationDedupPolicy.enabledDefaults()); - } }