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;
* 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