diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index df248226..890e8e2c 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -552,7 +552,11 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis 긴 lease 를 약속하는 건 false contract 다. shipped 와이어링에선 `leaseTtl == configuredTtl` (둘 다 `LockSettings.leaseTtl()` 바인딩)이라 이 가드는 mis-wired 호출자/테스트에서만 fail-fast 로 발동한다. -- 반환 핸들은 `lock::unlock` 람다(SAM 인터페이스 충족). `InterruptedException` 은 interrupt flag +- 반환 핸들의 `close()` 는 닫힘 표시가 없을 때만 `lock.unlock()` 을 부른다. 락을 얻은 스레드의 + close 는 unlock 전에 표시를 남기므로, unlock 이 실패해도 다음 `close()` 는 아무것도 하지 않는다(포트의 + idempotent 약속). registry 락은 스레드에 묶이고 재진입하므로, 같은 핸들을 다시 unlock 하면 같은 + 스레드가 쥔 다른 핸들의 보유가 풀린다. 다른 스레드의 `close()` 는 표시를 남기지 않고 registry 락처럼 + 실패해서, 얻은 스레드가 여전히 풀 수 있다. `InterruptedException` 은 interrupt flag 를 복원하고 `LockAcquisitionTimeoutException` 으로 변환한다. ### TTL 주의 (SI 7.0) @@ -563,7 +567,7 @@ provider 선택(flag → bean → registry)의 정본은 설정 코드 `lock/Dis 함께 자동으로 떨군다. ### SI-LOCK-C5 — lease 만료 후 release -반환 핸들은 `lock::unlock` 이다. lease TTL 이 `close()` 전에 만료된 `JdbcLockRegistry` +락을 얻은 스레드의 첫 `close()` 가 `lock.unlock()` 을 부른다. lease TTL 이 `close()` 전에 만료된 `JdbcLockRegistry` 의 경우, 내부 `JdbcLock.unlock()` 이 `ConcurrentModificationException` 을 던진다(row 가 이미 회수됨). 이 어댑터는 여기서 일부러 잡지 않는다 — metered `distributedLockProvider` 데코레이터 (이 모듈의 `DistributedLockPersistenceConfig`가 감싼 `MeteredDistributedLock`)가 SI-LOCK-C5 계약을 소유한다: 로그 + `lock.lease.expired` metric 후 `close()` 에서 diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java index ce984c7a..fdf86fb4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java @@ -4,6 +4,7 @@ import dev.caskeleton.application.lock.DistributedLockPort; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import java.time.Duration; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import org.springframework.integration.support.locks.DistributedLock; import org.springframework.integration.support.locks.LockRegistry; @@ -52,6 +53,27 @@ public class LockRegistryDistributedLock implements DistributedLockPort { if (!acquired) { throw new LockAcquisitionTimeoutException(key, waitTime); } - return l::unlock; + return releasedOnceByOwner(l); + } + + /** + * The handle's {@code close()} must be idempotent (port contract), and registry locks are + * thread-bound and reentrant: unlocking again would release another handle's hold. The first + * close on the acquiring thread marks the handle before it unlocks, so a later close does nothing + * even when that unlock failed. A close on another thread leaves no mark and fails as the + * registry lock does, so the acquiring thread can still release. + */ + private static dev.caskeleton.application.lock.DistributedLock releasedOnceByOwner(Lock lock) { + Thread owner = Thread.currentThread(); + AtomicBoolean closed = new AtomicBoolean(); + return () -> { + if (closed.get()) { + return; + } + if (Thread.currentThread() == owner) { + closed.set(true); + } + lock.unlock(); + }; } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java index 93c52c49..4ee02617 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java @@ -2,18 +2,24 @@ package dev.caskeleton.adapter.outbound.persistence.lock; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.lock.DistributedLock; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import java.time.Duration; +import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; import org.junit.jupiter.api.Test; import org.springframework.integration.support.locks.DefaultLockRegistry; /** * Pure unit tests for {@link LockRegistryDistributedLock} over an in-process {@link - * DefaultLockRegistry} (no database, no Spring context). + * DefaultLockRegistry} (no database, no Spring context). The failed-release tests use a registry + * whose lock fails on release instead. * *

Determinism strategy

* @@ -21,11 +27,16 @@ import org.springframework.integration.support.locks.DefaultLockRegistry; * The background thread acquires the lock and signals readiness before the main thread makes a * contending attempt. The background thread releases the lock only after the main thread's * assertion completes. This avoids timing-based sleeps. + * + *

Tests whose handles must stay on the test thread contend from another thread instead, through + * {@code onAnotherThread}, which waits at most {@code OTHER_THREAD_WAIT}. */ class LockRegistryDistributedLockTest { private static final Duration CONFIGURED_TTL = Duration.ofSeconds(30); private static final Duration SHORT_WAIT = Duration.ofMillis(50); + // Bounds the wait for work on another thread: far above SHORT_WAIT, so only a hang reaches it. + private static final Duration OTHER_THREAD_WAIT = Duration.ofSeconds(5); private LockRegistryDistributedLock adapter() { return new LockRegistryDistributedLock(new DefaultLockRegistry(), CONFIGURED_TTL); @@ -146,4 +157,128 @@ class LockRegistryDistributedLockTest { assertThat(second).isNotNull(); second.close(); } + + // ------------------------------------------------------------------ + // close() is idempotent and releases only its own hold + // ------------------------------------------------------------------ + + @Test + void closingTheOnlyHandleTwiceDoesNotThrow() { + // given + DistributedLock held = adapter().tryAcquire("key-6", SHORT_WAIT, CONFIGURED_TTL); + held.close(); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isNull(); + } + + /** + * One thread holds a key twice through reentrant handles a and b. Closing a again must not drop + * b's hold, so another thread still times out while b is open. + */ + @Test + void closingOneOfTwoReentrantHandlesTwiceKeepsTheOtherHold() throws Exception { + // given + LockRegistryDistributedLock sut = adapter(); + String key = "key-7"; + DistributedLock a = sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL); + DistributedLock b = sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL); + a.close(); + a.close(); + + // when + Throwable contender = onAnotherThread(() -> acquireAndRelease(sut, key)); + + // then + assertThat(contender) + .as("another thread's acquire while handle b is still open") + .isInstanceOfSatisfying( + LockAcquisitionTimeoutException.class, e -> assertThat(e.key()).isEqualTo(key)); + b.close(); + } + + @Test + void aFailedReleasePropagatesTheRegistryException() { + // given + ReleaseFailingLock lock = new ReleaseFailingLock(); + DistributedLock held = + new LockRegistryDistributedLock(key -> lock, CONFIGURED_TTL) + .tryAcquire("key-8", SHORT_WAIT, CONFIGURED_TTL); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isSameAs(lock.failure); + } + + @Test + void closingAgainAfterAFailedReleaseDoesNotThrow() { + // given + ReleaseFailingLock lock = new ReleaseFailingLock(); + DistributedLock held = + new LockRegistryDistributedLock(key -> lock, CONFIGURED_TTL) + .tryAcquire("key-9", SHORT_WAIT, CONFIGURED_TTL); + assertThat(catchThrowable(held::close)) + .as("given: the first close fails") + .isSameAs(lock.failure); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isNull(); + } + + /** + * A close from a thread that does not hold the lock fails and must not use up the handle: the + * acquiring thread's close afterwards still releases the key. + */ + @Test + void theOwnerStillReleasesAfterAnotherThreadsCloseFailed() throws Exception { + // given + LockRegistryDistributedLock sut = adapter(); + String key = "key-10"; + DistributedLock held = sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL); + assertThat(onAnotherThread(() -> catchThrowable(held::close))) + .as("given: a close from another thread fails") + .isInstanceOf(IllegalMonitorStateException.class); + held.close(); + + // when + Throwable contender = onAnotherThread(() -> acquireAndRelease(sut, key)); + + // then + assertThat(contender).as("another thread's acquire after the owner's close").isNull(); + } + + private static Throwable acquireAndRelease(LockRegistryDistributedLock sut, String key) { + return catchThrowable(() -> sut.tryAcquire(key, SHORT_WAIT, CONFIGURED_TTL).close()); + } + + /** Runs {@code attempt} on a new thread, which the lock sees as another owner, within a bound. */ + private static Throwable onAnotherThread(Callable attempt) throws Exception { + FutureTask task = new FutureTask<>(attempt); + new Thread(task, "lock-contender").start(); + return task.get(OTHER_THREAD_WAIT.toMillis(), TimeUnit.MILLISECONDS); + } + + /** + * A registry lock whose release frees the local hold and then fails, as {@code JdbcLock.unlock()} + * does when deleting the lock row fails. + */ + @SuppressWarnings("serial") + private static final class ReleaseFailingLock extends ReentrantLock { + + private final RuntimeException failure = new IllegalStateException("lock row delete failed"); + + @Override + public void unlock() { + super.unlock(); + throw failure; + } + } } diff --git a/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java b/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java index d2b5c9e7..5c699f30 100644 --- a/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java +++ b/src/application/core/src/testFixtures/java/dev/caskeleton/application/lock/testkit/DistributedLockContract.java @@ -62,6 +62,20 @@ public abstract class DistributedLockContract { assertThat(thrown).isNull(); } + /** {@link DistributedLock#close()} is idempotent: a handle closed again must not throw. */ + @Test + void closingAReleasedHandleAgainDoesNotThrow() { + // given + DistributedLock held = firstInstance().tryAcquire(uniqueKey(), SHORT_WAIT, LEASE); + held.close(); + + // when + Throwable thrown = catchThrowable(held::close); + + // then + assertThat(thrown).isNull(); + } + @Test void differentKeysDoNotContend() { // given