diff --git a/src/application/core/README.md b/src/application/core/README.md index d6001379..c8bfc15d 100644 --- a/src/application/core/README.md +++ b/src/application/core/README.md @@ -554,7 +554,10 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt - **트랜잭션 커밋 순서 불변식(D4)**: 반환된 핸들은 보호 작업의 DB 트랜잭션이 **커밋된 후에만** 해제해야 한다. 트랜잭션 안(커밋 전)에서 해제하면 lost-update 경합이 생긴다 — 두 번째 스레드가 락을 얻어, 첫 트랜잭션의 쓰기가 DB 에 보이기 전에 자신의 read-modify-write 를 시작한다. - - 올바른 패턴: `tryAcquire` → `try { txPort.inWrite(...) } finally { lock.close() }`(커밋 후 해제). + - 올바른 패턴: 트랜잭션 밖에서 `tryAcquire` → `try { txPort.inRootWrite(...) } finally { lock.close() }`. + 호출이 끝나면 커밋·롤백·결과 불명 어느 쪽이든 해제한다. 이 문서의 「커밋 후에만」은 성공 경로의 말이다. + 결과 불명이면 해제 뒤에 커밋이 보일 수 있고 그 틈은 DB 제약이 막는다(D6). `inWrite`는 바깥 트랜잭션에 + 합류해 커밋 전에 돌아올 수 있어 쓰지 않는다. 이미 트랜잭션 안이면(inbox handler 등) 이 패턴을 쓸 수 없다. - 금지된 역순: `inWrite` 콜백 안에서 `lock.close()`(커밋 전 해제 → 다른 스레드가 stale 상태를 본다). - **효율 락이지 정합성 락이 아니다(D6)**: 이 락은 경합·불필요한 재시도를 줄이는 *효율* 장치다. 정합성(중복·충돌 쓰기 방지)은 여전히 DB 제약(유니크 인덱스·낙관적 동시성)이 강제한다. 이 락 diff --git a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java index 61b666d3..d47be2e8 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java @@ -6,16 +6,35 @@ import java.time.Duration; * Outbound port for acquiring a distributed lock — the only dependency the application layer may * use for coordinated mutual exclusion (no lock client / SQL imports in use cases). {@code * tryAcquire} is a try-lock with a finite {@code waitTime} and a crash-safety {@code leaseTtl}; the - * handle must be released only after the protected transaction commits. This is an efficiency lock, - * not a correctness lock (DB constraints still guard correctness). See README for the full - * rationale. + * handle must be released only after the protected transaction call ends, never inside its + * callback. This is an efficiency lock, not a correctness lock (DB constraints still guard + * correctness). See README for the full rationale. */ public interface DistributedLockPort { /** * Attempts to acquire the distributed lock identified by {@code key}, blocking for at most {@code * waitTime}. Returns a {@link DistributedLock} whose {@code close()} releases the lock — call it - * only after the protected transaction commits. See README for lease-expiry-on-release behaviour. + * only after the protected transaction call ends. See README for lease-expiry-on-release + * behaviour. + * + *

Acquire outside any transaction and release in {@code finally}, also when the transaction + * fails, but never inside its callback — releasing before the commit lets the next holder act on + * stale state, before this transaction's writes are visible. The after-commit rule of {@link + * DistributedLock#close()} describes the success path: on rollback or an unknown outcome release + * anyway. After an unknown outcome the commit may become visible after the release, and only DB + * constraints guard that window. A caller already in a transaction, such as an inbox handler, + * cannot use this shape: {@code inWrite} would join that transaction and return before its + * commit. + * + *

{@code
+   * DistributedLock lock = port.tryAcquire(key, waitTime, leaseTtl);
+   * try {
+   *   tx.inRootWrite(() -> work()); // refuses an ambient transaction; returns after the commit
+   * } finally {
+   *   lock.close(); // the transaction call ended: committed, rolled back, or outcome unknown
+   * }
+   * }
* * @param key the lock identifier; must be non-null and non-blank * @param waitTime the maximum time to wait for the lock; must be finite and positive diff --git a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java index b1c1f0ab..47441cb0 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java @@ -1,13 +1,14 @@ package dev.caskeleton.application.lock; 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.application.lock.testkit.InMemoryDistributedLock; import java.time.Duration; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; /** @@ -20,8 +21,6 @@ import org.junit.jupiter.api.Test; *
    *
  1. {@code tryAcquire} returns a non-null handle. *
  2. {@code close()} releases the lock so a subsequent acquire on the same key succeeds. - *
  3. A try-finally release pattern demonstrates the D4 ordering (work inside try, release in - * finally after work completes). *
  4. A second attempt while the key is held times out and throws {@link * LockAcquisitionTimeoutException} carrying the right key. *
@@ -30,6 +29,9 @@ class DistributedLockPortContractTest { private static final Duration SHORT_WAIT = Duration.ofMillis(50); private static final Duration LEASE_TTL = Duration.ofSeconds(30); + // Bounds each wait on the holder thread: far above SHORT_WAIT, so only a holder that never + // acquires or never ends reaches it, and the test then fails instead of hanging. + private static final Duration HOLDER_WAIT = Duration.ofSeconds(5); // ----------------------------------------------------------------------- // Tests @@ -57,38 +59,6 @@ class DistributedLockPortContractTest { second.close(); } - /** - * Demonstrates the D4 ordering invariant: the lock handle is released AFTER the protected work - * completes (represented here by a side-effect list), not before. - * - *

Canonical pattern (from port Javadoc): - * - *

-   *   DistributedLock lock = port.tryAcquire(key, waitTime, leaseTtl);
-   *   try {
-   *       txPort.inWrite(() -> { ... protected work ... });  // commit returns here
-   *   } finally {
-   *       lock.close();                                       // release AFTER commit
-   *   }
-   * 
- */ - @Test - void tryFinallyReleaseAfterWorkDemonstratesD4Ordering() { - DistributedLockPort port = new InMemoryDistributedLock(); - List events = new ArrayList<>(); - - DistributedLock lock = port.tryAcquire("payment/99", SHORT_WAIT, LEASE_TTL); - try { - events.add("work-done"); // represents: tx.inWrite(() -> { ... }) - } finally { - lock.close(); // release AFTER work (D4 ordering) - events.add("lock-released"); - } - - // work must complete before release - assertThat(events).containsExactly("work-done", "lock-released"); - } - /** * While the lock is held, a second attempt on the same key must time out and throw {@link * LockAcquisitionTimeoutException} carrying the correct key. @@ -99,13 +69,14 @@ class DistributedLockPortContractTest { @Test void timeoutWhileKeyIsHeldThrowsLockAcquisitionTimeoutExceptionWithCorrectKey() throws InterruptedException { - + // given InMemoryDistributedLock port = new InMemoryDistributedLock(); String key = "inventory/sku-99"; // Hold the lock in a background thread until the main thread's test completes. CountDownLatch held = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); + AtomicReference holderError = new AtomicReference<>(); Thread holder = new Thread( @@ -121,22 +92,32 @@ class DistributedLockPortContractTest { } }, "lock-holder"); + holder.setUncaughtExceptionHandler((thread, error) -> holderError.set(error)); holder.start(); + try { + boolean acquired = held.await(HOLDER_WAIT.toMillis(), TimeUnit.MILLISECONDS); + // the handler swallows the holder's stack trace, so report its error before the timeout + assertThat(holderError.get()).as("holder thread acquired the lock without an error").isNull(); + assertThat(acquired).as("holder thread acquired the lock within %s", HOLDER_WAIT).isTrue(); - held.await(); // wait for the holder thread to acquire the lock - - // Now try to acquire from the main thread — must time out - assertThatThrownBy(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL)) - .isInstanceOf(LockAcquisitionTimeoutException.class) - .satisfies( - ex -> { - LockAcquisitionTimeoutException timeout = (LockAcquisitionTimeoutException) ex; - assertThat(timeout.key()).isEqualTo(key); - assertThat(timeout.waitTime()).isEqualTo(SHORT_WAIT); - }); - - release.countDown(); // unblock the holder thread - holder.join(1_000); // wait for holder to finish cleanly + // when & then: a second acquire from the main thread must time out + assertThatThrownBy(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL)) + .isInstanceOf(LockAcquisitionTimeoutException.class) + .satisfies( + ex -> { + LockAcquisitionTimeoutException timeout = (LockAcquisitionTimeoutException) ex; + assertThat(timeout.key()).isEqualTo(key); + assertThat(timeout.waitTime()).isEqualTo(SHORT_WAIT); + }); + } finally { + release.countDown(); // unblock the holder thread even when an assertion above fails + } + holder.join(HOLDER_WAIT.toMillis()); + assertThat(holder.isAlive()).as("holder thread ended within %s", HOLDER_WAIT).isFalse(); + assertThat(holderError.get()).as("holder thread ended without an error").isNull(); + assertThatCode(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL).close()) + .as("holder thread released the lock") + .doesNotThrowAnyException(); } @Test