review-followup Wave 3 라운드 3(P22): Redis runtime·SDK 분리, 좁은 semantic 포트, startup rule, lease fencing 계약

- 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) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 13:39:24 +09:00
co-authored by Claude Opus 5.5
parent 486d85a603
commit 4f4bd1fd34
283 changed files with 5499 additions and 5120 deletions
@@ -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);
}
}
@@ -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.
*
* <p>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.
*
* <p>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);
}
}
@@ -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.
*
* <p>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<String, Holding> 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();
}
}
}
}