From 0caf59e54a55cabd9b021e741eff81e90f0d37ca Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 21 Nov 2026 17:01:29 +0900 Subject: [PATCH] =?UTF-8?q?test(notification):=20=EC=95=8C=EB=A6=BC=20work?= =?UTF-8?q?er=20=EB=91=98=EC=9D=98=20claim=20=EC=88=98=C2=B7=EC=A7=80?= =?UTF-8?q?=ED=91=9C=C2=B7=EC=A2=85=EB=A3=8C=C2=B7pass=20=EC=8B=A4?= =?UTF-8?q?=ED=8C=A8=EB=A5=BC=20=EC=8B=9C=ED=97=98=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NotificationSchedulerWorker와 NotificationBackgroundWorkers에는 주석이 「예전 결함」이라 적은 고침 넷이 있다. batch를 동시 실행 허가보다 많이 claim하지 않기, 큐 깊이 gauge를 batch 크기가 아니라 backlog로 보고하기, close()가 polling 스레드를 join하기, pass 실패를 삼켜 일정이 이어지게 하기다. 이 클래스를 new로 만들어 동작을 보는 시험이 없어, 넷 중 어느 줄을 되돌려도 :composition:notification-platform test가 통과한다. worker 단위 시험 두 파일을 더한다. NotificationSchedulerWorkerTest는 허가 2·batch 10이면 claim 한도가 2인지, gauge 값이 backlog 조회 결과인지, close()가 진행 중인 claim이 끝난 뒤에야 돌아오는지 본다. 마지막 시험의 claim은 JDBC 호출처럼 interrupt에 멈추지 않고 close()가 먼저 돌아오는지 2초 동안 본다. join이 있으면 close()는 그 claim을 기다리므로 그 안에 돌아올 수 없다. NotificationBackgroundWorkersTest는 recovery pass가 첫 차례에 던져도 두 번째 차례가 불리는지 Mockito의 상한 있는 verify로 본다. sleep으로 기다리지 않는다. 유스케이스 여섯은 final 서비스를 받는 concrete 클래스라 같은 계층의 outbox relay 시험처럼 Mockito로 대신한다. application-notification testFixtures에는 이 유스케이스들이나 지표 포트의 fake가 없고, 그것을 쓰려면 이 leaf의 build.gradle을 바꿔야 해 항목 범위(시험 파일만) 밖이다. 버린 안: 실 DB 통합 시험으로만 보기. lane이 무겁고 이 규칙은 DB와 무관하다. 위험·한계: main 코드는 바꾸지 않았다. close 시험은 정상 경로에서 2초가 든다. 항목은 「close() 뒤 claim이 더 불리지 않음」이라 적었지만 loop가 shuttingDown을 먼저 보므로 join이 없어도 새 claim은 시작되지 않는다. join이 없을 때 남는 것은 close() 뒤에도 돌고 있는 claim이라 그것을 단언한다. 검증: desktop RED·GREEN은 PR 본문에 둔다. Refs: REV-BE-0028 --- .../NotificationBackgroundWorkersTest.java | 61 ++++++ .../NotificationSchedulerWorkerTest.java | 183 ++++++++++++++++++ 2 files changed, 244 insertions(+) create mode 100644 src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationBackgroundWorkersTest.java create mode 100644 src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationSchedulerWorkerTest.java diff --git a/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationBackgroundWorkersTest.java b/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationBackgroundWorkersTest.java new file mode 100644 index 00000000..a1898263 --- /dev/null +++ b/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationBackgroundWorkersTest.java @@ -0,0 +1,61 @@ +package dev.caskeleton.composition.notification; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import dev.caskeleton.application.notification.platform.callback.ReplayProviderEventsUseCase; +import dev.caskeleton.application.notification.platform.dispatch.ReconcileOutstandingAttemptsUseCase; +import dev.caskeleton.application.notification.platform.dispatch.RecoverAbandonedDeliveriesCommand; +import dev.caskeleton.application.notification.platform.dispatch.RecoverAbandonedDeliveriesUseCase; +import java.time.Duration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * A failed pass does not stop the schedule. An exception that escapes a task given to {@code + * scheduleWithFixedDelay} cancels every later run without a word, so a recovery pass that failed + * once would never run again while the process lived. + * + *

The three passes are concrete use case classes whose dependencies are final services of the + * application leaf, so they are Mockito stand-ins, and the failure is injected through the recovery + * pass. The replay and reconciliation passes go through the same wrapper in {@code schedule}, so + * one pass shows the rule for the three. The wait is Mockito's bounded verification, not a sleep: + * it ends at the second call. + */ +class NotificationBackgroundWorkersTest { + + private final RecoverAbandonedDeliveriesUseCase recovery = + mock(RecoverAbandonedDeliveriesUseCase.class); + private final ReplayProviderEventsUseCase replay = mock(ReplayProviderEventsUseCase.class); + private final ReconcileOutstandingAttemptsUseCase reconciliation = + mock(ReconcileOutstandingAttemptsUseCase.class); + + private NotificationBackgroundWorkers workers; + + @AfterEach + void closeWorkers() { + if (workers != null) { + workers.close(); + } + } + + @Test + void aRecoveryPassThatThrowsRunsAgainOnItsSchedule() { + // given + when(recovery.handle(any())) + .thenThrow(new IllegalStateException("lease store unavailable")) + .thenReturn(0); + workers = + new NotificationBackgroundWorkers( + recovery, replay, reconciliation, Duration.ofMillis(5), Duration.ofSeconds(5)); + + // when + workers.start(); + + // then + verify(recovery, timeout(10_000).atLeast(2)).handle(new RecoverAbandonedDeliveriesCommand()); + } +} diff --git a/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationSchedulerWorkerTest.java b/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationSchedulerWorkerTest.java new file mode 100644 index 00000000..9f5a9cc7 --- /dev/null +++ b/src/bootstrap/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationSchedulerWorkerTest.java @@ -0,0 +1,183 @@ +package dev.caskeleton.composition.notification; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties; +import dev.caskeleton.application.notification.platform.dispatch.ClaimDueDeliveriesCommand; +import dev.caskeleton.application.notification.platform.dispatch.ClaimDueDeliveriesUseCase; +import dev.caskeleton.application.notification.platform.dispatch.DispatchClaimedDeliveryUseCase; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; +import dev.caskeleton.application.notification.platform.observation.MeasureDispatchBacklogUseCase; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The scheduler worker's own rules: how much it claims, what it publishes as queue depth, and what + * "closed" means. Each of the three was a defect once (the comments in {@link + * NotificationSchedulerWorker} say which), and nothing constructed the worker to see them come + * back. + * + *

The worker is built with {@code new}, the way {@link NotificationWorkerConfiguration} builds + * it (README: the worker is not a bean of its own). Its collaborators are concrete use case classes + * whose dependencies are final services of the application leaf, so they are Mockito stand-ins + * here, as the outbox relay's scheduler tests stand in for theirs; nothing in this class depends on + * what the use cases do inside. The metrics port has no fake in a testFixtures set, and the one + * thing read from it is the gauge call, so it is a stand-in too. Time is never waited out: each + * step waits on a latch with a bound, and a bound that runs out fails the test. + */ +class NotificationSchedulerWorkerTest { + + private static final Duration LEASE = Duration.ofSeconds(30); + + private final ClaimDueDeliveriesUseCase claim = mock(ClaimDueDeliveriesUseCase.class); + private final DispatchClaimedDeliveryUseCase dispatch = + mock(DispatchClaimedDeliveryUseCase.class); + private final NotificationMetricsPort metrics = mock(NotificationMetricsPort.class); + private final MeasureDispatchBacklogUseCase backlog = mock(MeasureDispatchBacklogUseCase.class); + + private NotificationSchedulerWorker worker; + + @AfterEach + void closeWorker() { + if (worker != null) { + worker.close(); + } + } + + @Test + @DisplayName("동시 실행 허가가 2개면 batch가 10이어도 2건만 claim한다") + void aBatchLargerThanTheFreePermitsClaimsOnlyWhatCanStartNow() { + // given + when(claim.handle(any())).thenReturn(List.of()); + worker = worker(10, 2); + + // when + worker.runOnce(); + + // then + verify(claim).handle(new ClaimDueDeliveriesCommand("worker-1", 2, LEASE)); + } + + @Test + @DisplayName("큐 깊이 지표는 이번 batch 크기가 아니라 backlog 조회 결과다") + void theQueueDepthGaugeReportsTheBacklogRatherThanTheBatch() { + // given + when(claim.handle(any())).thenReturn(List.of()); + when(backlog.handle(any())).thenReturn(12_345L); + worker = worker(10, 2); + + // when + worker.runOnce(); + + // then + verify(metrics).gauge(NotificationMetricName.QUEUE_DEPTH, Map.of(), 12_345.0); + } + + /** + * A claim in flight when shutdown begins ends before close() returns. + * + *

The stand-in claim does not stop when interrupted, as a claim inside a JDBC call does not, + * and gives close() two seconds to return while it is still running. A close() that waits for the + * polling thread cannot return in that time, because the thread it waits for is the one running + * the claim; a close() that only asks the thread to stop returns at once, and the claim then ends + * with the worker already "closed" — the leases it took held by a process that has shut down. + * + *

The bound only decides how fast a missing join is caught: the correct close() returns false + * whatever the load, and a close() without the join that takes longer than the bound to return + * would let that one run pass. + */ + @Test + void closeReturnsOnlyAfterTheClaimInFlightHasEnded() throws InterruptedException { + // given + CountDownLatch claimStarted = new CountDownLatch(1); + CountDownLatch closeReturned = new CountDownLatch(1); + CountDownLatch claimEnded = new CountDownLatch(1); + AtomicReference closeHadReturnedWhenTheClaimEnded = new AtomicReference<>(); + when(claim.handle(any())) + .thenAnswer( + invocation -> { + claimStarted.countDown(); + closeHadReturnedWhenTheClaimEnded.set( + awaitIgnoringInterrupts(closeReturned, Duration.ofSeconds(2))); + claimEnded.countDown(); + return List.of(); + }); + worker = worker(10, 2); + worker.start(); + awaitOrFail(claimStarted, "the polling thread never claimed"); + + // when + try { + worker.close(); + } finally { + // The signal is close() returning, not a second action. + closeReturned.countDown(); + } + + // then + awaitOrFail(claimEnded, "the claim in flight never ended"); + assertThat(closeHadReturnedWhenTheClaimEnded).hasValue(false); + } + + private NotificationSchedulerWorker worker(int claimBatchSize, int maxGlobalConcurrency) { + return new NotificationSchedulerWorker( + claim, + dispatch, + metrics, + new NotificationDispatchProperties( + claimBatchSize, + LEASE, + Duration.ofSeconds(1), + maxGlobalConcurrency, + 0, + Duration.ofSeconds(1), + Duration.ofMinutes(5), + // Long enough that close() never gives up on the polling thread inside this test. + Duration.ofSeconds(30)), + backlog, + "worker-1"); + } + + private static void awaitOrFail(CountDownLatch latch, String failure) + throws InterruptedException { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new AssertionError(failure); + } + } + + /** + * Waits for the latch through interrupts, then hands the interrupt back to the thread. + * + * @return whether the latch opened within the bound + */ + private static boolean awaitIgnoringInterrupts(CountDownLatch latch, Duration bound) { + long deadline = System.nanoTime() + bound.toNanos(); + boolean interrupted = false; + try { + while (true) { + try { + return latch.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); + } catch (InterruptedException ignored) { + interrupted = true; + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } +} -- 2.54.0