feat!: 남은 리뷰 발견을 고치고 개발 매뉴얼과 기능 생성 명령을 더한다
문제: High·P1을 고친 뒤에도 P2·P3 약 90건이 남았다. 연결·구독·메시지 크기 상한이 없는 전송(WebSocket·gRPC·GraphQL deadline), 낙관적 충돌의 500, upsert 경쟁, Mongo 무제한 timeout, 샘플 목록 N+1, 갈라진 복사본 (TenantId 3벌, 이벤트 ID 문법 5곳, SQLState 표 2벌), 문서를 읽는 PR 테스트와 캐시를 막는 lane 설정 등이다. 새 기능을 어디에 어떤 순서로 만드는지 알려 주는 문서와 도구가 없었다. MinIO 공식 이미지가 사라져 객체 저장소 lane이 돌지 않았다. 방법: 영역별 묶음으로 실패 테스트를 먼저 쓰고 고쳤다. 고치는 중에 찾은 결함도 함께 고쳤다(durable operation id가 UUIDv4라 이벤트가 전부 DEAD, S3 어댑터 생성·작은 chunk 읽기 실패, Redis 조건부 기록의 EVALSHA 권한). MinIO는 pgsty/minio를 digest로 고정했다(Chainguard는 태그·실행 사용자· mc 이미지 문제로 버림). docs/manual/에 작업 순서와 판단 지점을 쓰고, scripts/new-feature.sh가 5개 leaf에 뼈대를 만든다. 생성→빌드→통과 왕복을 verifyFeatureScaffold가 mainCheck에서 본다. 묶음별 결과와 결정은 리뷰 README 14절에 있다. 위험·한계: 파생 서비스 동작이 바뀐다. JDBC batch 50 기본, 운영 jar에서 H2 제거, 트랜잭션 30초 제한, 격리 수준을 Hikari에서 고정, gRPC· WebSocket·GraphQL 새 한도, correlation ID 규칙 밖이면 서버가 교체, 샘플 키 오류 코드 IDEMPOTENCY_KEY_INVALID. 새 leaf 두 개 (composition:durable-operation, adapter:inbound:messaging)와 새 마이그레이션(postgresql V20·V21, notification V11·V12, sample V8_1, grpc-ledger V002)이 생긴다. V21 유일 인덱스는 기존 중복이 있으면 실패한다(runbook에 확인 쿼리). 검증: ci, mainCheck(생성 명령 왕복 포함), integrationCheck(MinIO 포함 전 컨테이너 lane), -p optional-platforms ci integrationCheck 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14절 BREAKING CHANGE: JDBC batch 기본 켜짐, H2 운영 의존 제거, 트랜잭션 기본 제한 30초, gRPC·WebSocket·GraphQL 서버 한도 기본값 추가, 샘플 Idempotency-Key 오류 코드 변경.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
plugins {
|
||||
id 'ca.java-library'
|
||||
id 'java-test-fixtures'
|
||||
}
|
||||
|
||||
// Optional notification application product. The generic application contracts remain in
|
||||
@@ -7,4 +8,10 @@ plugins {
|
||||
dependencies {
|
||||
implementation project(':application-core')
|
||||
implementation project(':shared-contract')
|
||||
|
||||
// Port contracts (`*Contract`) are abstract JUnit classes that the in-memory fakes here and the
|
||||
// PostgreSQL adapters (persistence-jpa's postgresqlIntegrationTest lane) both extend, so a use
|
||||
// case test passing on a fake says something about the real store (review 04-14).
|
||||
testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api'
|
||||
testFixturesImplementation 'org.assertj:assertj-core'
|
||||
}
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
# This is a Gradle generated file for dependency locking.
|
||||
# Manual edits can break the build and are not advised.
|
||||
# This file is expected to be part of source control.
|
||||
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
|
||||
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
|
||||
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
|
||||
com.github.spotbugs:spotbugs:4.10.2=spotbugs
|
||||
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
|
||||
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
|
||||
com.google.code.gson:gson:2.13.2=spotbugs
|
||||
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
|
||||
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
|
||||
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.guava:guava:33.6.0-jre=checkstyle
|
||||
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
|
||||
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
|
||||
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
|
||||
commons-beanutils:commons-beanutils:1.11.0=checkstyle
|
||||
commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
|
||||
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
jaxen:jaxen:2.0.6=spotbugs
|
||||
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
|
||||
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
|
||||
org.antlr:antlr4-runtime:4.13.2=checkstyle
|
||||
org.apache.bcel:bcel:6.12.0=spotbugs
|
||||
@@ -50,32 +50,32 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
|
||||
org.apache.xbean:xbean-reflect:3.7=checkstyle
|
||||
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
|
||||
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
|
||||
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath
|
||||
org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
|
||||
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
|
||||
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
|
||||
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
|
||||
org.dom4j:dom4j:2.2.0=spotbugs
|
||||
org.javassist:javassist:3.28.0-GA=checkstyle
|
||||
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath
|
||||
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath
|
||||
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
|
||||
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
org.junit:junit-bom:6.1.0=spotbugs
|
||||
org.mockito:mockito-core:5.20.0=mockitoAgent
|
||||
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
|
||||
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath
|
||||
org.ow2.asm:asm-analysis:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-commons:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-tree:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-util:9.10.1=spotbugs
|
||||
org.ow2.asm:asm:9.10.1=spotbugs
|
||||
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
|
||||
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor
|
||||
org.reflections:reflections:0.10.2=checkstyle
|
||||
org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j
|
||||
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
|
||||
|
||||
+14
-1
@@ -1,6 +1,19 @@
|
||||
package dev.caskeleton.application.notification.platform.api;
|
||||
|
||||
/** Tenant boundary every repository query must carry. */
|
||||
/**
|
||||
* Tenant boundary every repository query must carry.
|
||||
*
|
||||
* <p><b>A second tenant type, kept on purpose and only for now.</b> The repository's tenant grammar
|
||||
* is application-core's {@link dev.caskeleton.application.tenant.TenantId}, and every new write
|
||||
* here already has to match it ({@code WritableTenant}). This type stays lenient — non-blank, at
|
||||
* most 100 characters — because it is also what stored rows are read back into, and a row written
|
||||
* before writes adopted the shared grammar (a space, a path character) must stay readable.
|
||||
*
|
||||
* <p>To fold it into the shared type: run, on every deployment's notification schema, a query for
|
||||
* {@code tenant_id} values outside {@code ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$} in each table that has
|
||||
* the column; once none exist, add a CHECK constraint migration and replace this type. The template
|
||||
* default writes only {@code default}, which already matches.
|
||||
*/
|
||||
public record TenantId(String value) {
|
||||
|
||||
private static final int MAX_LENGTH = 100;
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
/** The in-memory fake held to the same contract as the PostgreSQL adapter. */
|
||||
class InMemoryPreferenceStoreTest extends PreferenceStoreContract {
|
||||
|
||||
private InMemoryPreferenceStore store;
|
||||
|
||||
@BeforeEach
|
||||
void freshStore() {
|
||||
store = new InMemoryPreferenceStore();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PreferenceStorePort store() {
|
||||
return store;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected <T> T inTransaction(Supplier<T> work) {
|
||||
return work.get();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
/** The in-memory fake held to the same contract as the PostgreSQL adapter. */
|
||||
class InMemorySuppressionStoreTest extends SuppressionStoreContract {
|
||||
|
||||
private InMemorySuppressionStore store;
|
||||
|
||||
@BeforeEach
|
||||
void freshStore() {
|
||||
store = new InMemorySuppressionStore();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SuppressionStorePort store() {
|
||||
return store;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected <T> T inTransaction(Supplier<T> work) {
|
||||
return work.get();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.api.TenantId;
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceRecord;
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* A preference store with the semantics the PostgreSQL adapter must also have: one record per
|
||||
* tenant and recipient, and a later save replaces the earlier one. {@link PreferenceStoreContract}
|
||||
* holds this fake and the adapter to the same cases.
|
||||
*/
|
||||
public final class InMemoryPreferenceStore implements PreferenceStorePort {
|
||||
|
||||
private record Key(TenantId tenantId, String recipientRef) {}
|
||||
|
||||
private final Map<Key, PreferenceRecord> records = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public Optional<PreferenceRecord> find(TenantId tenantId, String recipientRef) {
|
||||
Objects.requireNonNull(tenantId, "tenantId");
|
||||
Objects.requireNonNull(recipientRef, "recipientRef");
|
||||
return Optional.ofNullable(records.get(new Key(tenantId, recipientRef)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreferenceRecord save(PreferenceRecord record) {
|
||||
Objects.requireNonNull(record, "record");
|
||||
records.put(new Key(record.tenantId(), record.recipientRef()), record);
|
||||
return record;
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.api.TenantId;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionEntry;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionId;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionReason;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A suppression store with the semantics the PostgreSQL adapter must also have.
|
||||
*
|
||||
* <p>One entry per tenant, target fingerprint and reason. A second upsert of the same key refreshes
|
||||
* the window and the source of the entry already there and keeps its id, scope and category — the
|
||||
* same columns the adapter's {@code ON CONFLICT} branch leaves alone. {@link
|
||||
* SuppressionStoreContract} holds this fake and the adapter to the same cases.
|
||||
*/
|
||||
public final class InMemorySuppressionStore implements SuppressionStorePort {
|
||||
|
||||
private record Key(TenantId tenantId, String normalizedTargetHmac, SuppressionReason reason) {}
|
||||
|
||||
private final Map<Key, SuppressionEntry> entries = new LinkedHashMap<>();
|
||||
|
||||
@Override
|
||||
public synchronized List<SuppressionEntry> activeFor(
|
||||
TenantId tenantId, String targetFingerprint, Instant at) {
|
||||
Objects.requireNonNull(tenantId, "tenantId");
|
||||
Objects.requireNonNull(targetFingerprint, "targetFingerprint");
|
||||
Objects.requireNonNull(at, "at");
|
||||
return entries.values().stream()
|
||||
.filter(entry -> entry.tenantId().equals(tenantId))
|
||||
.filter(entry -> entry.normalizedTargetHmac().equals(targetFingerprint))
|
||||
.filter(entry -> entry.activeAt(at))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized SuppressionEntry upsert(SuppressionEntry entry) {
|
||||
Objects.requireNonNull(entry, "entry");
|
||||
Key key = new Key(entry.tenantId(), entry.normalizedTargetHmac(), entry.reason());
|
||||
SuppressionEntry stored =
|
||||
Optional.ofNullable(entries.get(key))
|
||||
.map(
|
||||
existing ->
|
||||
new SuppressionEntry(
|
||||
existing.id(),
|
||||
existing.tenantId(),
|
||||
existing.scope(),
|
||||
entry.reason(),
|
||||
existing.normalizedTargetHmac(),
|
||||
existing.notificationCategory(),
|
||||
entry.effectiveAt(),
|
||||
entry.expiresAt(),
|
||||
entry.source()))
|
||||
.orElse(entry);
|
||||
entries.put(key, stored);
|
||||
return stored;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Optional<SuppressionEntry> remove(TenantId tenantId, SuppressionId id) {
|
||||
Objects.requireNonNull(tenantId, "tenantId");
|
||||
Objects.requireNonNull(id, "id");
|
||||
Optional<Key> key =
|
||||
entries.entrySet().stream()
|
||||
.filter(candidate -> candidate.getValue().tenantId().equals(tenantId))
|
||||
.filter(candidate -> candidate.getValue().id().equals(id))
|
||||
.map(Map.Entry::getKey)
|
||||
.findFirst();
|
||||
return key.map(entries::remove);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Two writes of the same key whose transactions overlap, in an order that does not depend on luck.
|
||||
*
|
||||
* <p>The first write runs and then holds its transaction open. The second starts while the first is
|
||||
* still uncommitted — the moment a find-then-insert reads "absent" twice — and the first commits
|
||||
* only once the second has either finished or had time to block on the first's row. A store that
|
||||
* has no transactions simply runs the two one after the other, which is the answer it must give
|
||||
* anyway.
|
||||
*/
|
||||
final class OverlappingWrites {
|
||||
|
||||
private static final Duration SECOND_WRITE_HEAD_START = Duration.ofMillis(500);
|
||||
private static final Duration LIMIT = Duration.ofSeconds(30);
|
||||
|
||||
private OverlappingWrites() {}
|
||||
|
||||
/**
|
||||
* Runs both writes and returns their results, first then second.
|
||||
*
|
||||
* @param inTransaction runs one unit of work in one committed transaction of the store
|
||||
* @param first the write whose transaction is held open
|
||||
* @param second the write that starts while the first is uncommitted
|
||||
* @return both results; a write that failed fails this call with its cause
|
||||
*/
|
||||
static <T> List<T> run(
|
||||
Function<Supplier<T>, T> inTransaction, Supplier<T> first, Supplier<T> second) {
|
||||
CountDownLatch firstWrote = new CountDownLatch(1);
|
||||
CountDownLatch releaseFirst = new CountDownLatch(1);
|
||||
ExecutorService threads = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<T> firstResult =
|
||||
threads.submit(
|
||||
() ->
|
||||
inTransaction.apply(
|
||||
() -> {
|
||||
T written = first.get();
|
||||
firstWrote.countDown();
|
||||
await(releaseFirst);
|
||||
return written;
|
||||
}));
|
||||
if (!firstWrote.await(LIMIT.toMillis(), TimeUnit.MILLISECONDS)) {
|
||||
throw new IllegalStateException("the first write never finished its statement");
|
||||
}
|
||||
Future<T> secondResult = threads.submit(() -> inTransaction.apply(second));
|
||||
try {
|
||||
secondResult.get(SECOND_WRITE_HEAD_START.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (TimeoutException blockedOnTheFirst) {
|
||||
// Expected on a database: the second write waits for the first's uncommitted row.
|
||||
} catch (ExecutionException failed) {
|
||||
// Reported below, after the first transaction has been allowed to finish.
|
||||
}
|
||||
releaseFirst.countDown();
|
||||
return List.of(
|
||||
firstResult.get(LIMIT.toMillis(), TimeUnit.MILLISECONDS),
|
||||
secondResult.get(LIMIT.toMillis(), TimeUnit.MILLISECONDS));
|
||||
} catch (ExecutionException failed) {
|
||||
throw new AssertionError("an overlapping write failed", failed.getCause());
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("interrupted while racing two writes", interrupted);
|
||||
} catch (TimeoutException stuck) {
|
||||
throw new AssertionError("an overlapping write did not finish", stuck);
|
||||
} finally {
|
||||
releaseFirst.countDown();
|
||||
threads.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private static void await(CountDownLatch latch) {
|
||||
try {
|
||||
if (!latch.await(LIMIT.toMillis(), TimeUnit.MILLISECONDS)) {
|
||||
throw new IllegalStateException("the first write was never released");
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.api.TenantId;
|
||||
import dev.caskeleton.application.notification.platform.api.routing.Channel;
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceRecord;
|
||||
import dev.caskeleton.application.notification.platform.policy.PreferenceStorePort;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What every {@link PreferenceStorePort} promises, run against the in-memory fake and the
|
||||
* PostgreSQL adapter alike.
|
||||
*
|
||||
* <p>{@code updatedAt} is not compared: the adapter stamps it from its own clock.
|
||||
*/
|
||||
public abstract class PreferenceStoreContract {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z");
|
||||
private static final TenantId TENANT = new TenantId("tenant-a");
|
||||
private static final TenantId OTHER_TENANT = new TenantId("tenant-b");
|
||||
private static final String RECIPIENT = "user-1";
|
||||
|
||||
/** The store under test, empty at the start of each test. */
|
||||
protected abstract PreferenceStorePort store();
|
||||
|
||||
/** Runs {@code work} in one committed write transaction of the store under test. */
|
||||
protected abstract <T> T inTransaction(Supplier<T> work);
|
||||
|
||||
@Test
|
||||
@DisplayName("저장한 적 없는 수신자의 선호 설정은 비어 있다")
|
||||
void aRecipientWithoutAPreferenceHasNone() {
|
||||
// when
|
||||
Optional<PreferenceRecord> found = store().find(TENANT, RECIPIENT);
|
||||
|
||||
// then
|
||||
assertThat(found).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("저장한 선호 설정을 같은 테넌트에서 다시 읽는다")
|
||||
void aSavedPreferenceIsFoundInItsTenant() {
|
||||
// given
|
||||
save(preference(List.of(Channel.PUSH, Channel.EMAIL), Set.of(Channel.SMS)));
|
||||
|
||||
// when
|
||||
Optional<PreferenceRecord> found = store().find(TENANT, RECIPIENT);
|
||||
|
||||
// then
|
||||
assertThat(found)
|
||||
.get()
|
||||
.extracting(PreferenceRecord::preferredOrder, PreferenceRecord::mutedChannels)
|
||||
.containsExactly(List.of(Channel.PUSH, Channel.EMAIL), Set.of(Channel.SMS));
|
||||
assertThat(store().find(OTHER_TENANT, RECIPIENT)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다시 저장하면 나중 값이 이전 값을 대신한다")
|
||||
void aLaterSaveReplacesTheEarlierOne() {
|
||||
// given
|
||||
save(preference(List.of(Channel.PUSH), Set.of()));
|
||||
|
||||
// when
|
||||
save(preference(List.of(Channel.EMAIL, Channel.SMS), Set.of(Channel.PUSH)));
|
||||
|
||||
// then
|
||||
assertThat(store().find(TENANT, RECIPIENT))
|
||||
.get()
|
||||
.extracting(PreferenceRecord::preferredOrder, PreferenceRecord::mutedChannels)
|
||||
.containsExactly(List.of(Channel.EMAIL, Channel.SMS), Set.of(Channel.PUSH));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("첫 선호 설정 저장이 동시에 두 번 와도 둘 다 성공하고 나중 값이 남는다")
|
||||
void twoOverlappingFirstSavesBothSucceedAndTheLaterWins() {
|
||||
// given
|
||||
PreferenceRecord first = preference(List.of(Channel.PUSH), Set.of());
|
||||
PreferenceRecord second = preference(List.of(Channel.EMAIL), Set.of(Channel.PUSH));
|
||||
|
||||
// when
|
||||
List<PreferenceRecord> results =
|
||||
OverlappingWrites.run(
|
||||
this::inTransaction, () -> store().save(first), () -> store().save(second));
|
||||
|
||||
// then
|
||||
assertThat(results).hasSize(2);
|
||||
assertThat(store().find(TENANT, RECIPIENT))
|
||||
.as("the write that committed last is the preference")
|
||||
.get()
|
||||
.extracting(PreferenceRecord::preferredOrder)
|
||||
.isEqualTo(List.of(Channel.EMAIL));
|
||||
}
|
||||
|
||||
private PreferenceRecord save(PreferenceRecord record) {
|
||||
return inTransaction(() -> store().save(record));
|
||||
}
|
||||
|
||||
private static PreferenceRecord preference(List<Channel> preferred, Set<Channel> muted) {
|
||||
return new PreferenceRecord(TENANT, RECIPIENT, preferred, muted, NOW);
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package dev.caskeleton.application.notification.platform.policy.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.notification.platform.api.TenantId;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionEntry;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionId;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionReason;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionScope;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionSource;
|
||||
import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* What every {@link SuppressionStorePort} promises, run against the in-memory fake and the
|
||||
* PostgreSQL adapter alike.
|
||||
*
|
||||
* <p>Writes go through {@link #inTransaction}, because the real store refuses a write without a
|
||||
* caller transaction, and because the race case needs two transactions that overlap.
|
||||
*/
|
||||
public abstract class SuppressionStoreContract {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-11-01T09:00:00Z");
|
||||
private static final TenantId TENANT = new TenantId("tenant-a");
|
||||
private static final TenantId OTHER_TENANT = new TenantId("tenant-b");
|
||||
private static final String TARGET = "a".repeat(64);
|
||||
|
||||
/** The store under test, empty at the start of each test. */
|
||||
protected abstract SuppressionStorePort store();
|
||||
|
||||
/** Runs {@code work} in one committed write transaction of the store under test. */
|
||||
protected abstract <T> T inTransaction(Supplier<T> work);
|
||||
|
||||
@Test
|
||||
@DisplayName("저장한 수신 거부는 유효 기간 안에서 조회된다")
|
||||
void anUpsertedEntryIsActiveInsideItsWindow() {
|
||||
// given
|
||||
SuppressionEntry stored = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null));
|
||||
|
||||
// when
|
||||
List<SuppressionEntry> active = store().activeFor(TENANT, TARGET, NOW.plusSeconds(1));
|
||||
|
||||
// then
|
||||
assertThat(active).containsExactly(stored);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 대상과 사유를 다시 저장하면 기존 항목의 기간과 출처만 갱신된다")
|
||||
void aSecondUpsertOfTheSameKeyRefreshesTheExistingEntry() {
|
||||
// given
|
||||
SuppressionEntry first = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null));
|
||||
SuppressionEntry refresh =
|
||||
new SuppressionEntry(
|
||||
new SuppressionId(UUID.randomUUID()),
|
||||
TENANT,
|
||||
SuppressionScope.RECIPIENT,
|
||||
SuppressionReason.HARD_BOUNCE,
|
||||
TARGET,
|
||||
Optional.of("marketing"),
|
||||
NOW.plus(Duration.ofHours(1)),
|
||||
Optional.of(NOW.plus(Duration.ofDays(1))),
|
||||
SuppressionSource.ADMIN);
|
||||
|
||||
// when
|
||||
SuppressionEntry refreshed = upsert(refresh);
|
||||
|
||||
// then
|
||||
assertThat(refreshed)
|
||||
.isEqualTo(
|
||||
new SuppressionEntry(
|
||||
first.id(),
|
||||
TENANT,
|
||||
first.scope(),
|
||||
SuppressionReason.HARD_BOUNCE,
|
||||
TARGET,
|
||||
first.notificationCategory(),
|
||||
NOW.plus(Duration.ofHours(1)),
|
||||
Optional.of(NOW.plus(Duration.ofDays(1))),
|
||||
SuppressionSource.ADMIN));
|
||||
assertThat(store().activeFor(TENANT, TARGET, NOW.plus(Duration.ofHours(2))))
|
||||
.containsExactly(refreshed);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("사유가 다르면 같은 대상이라도 별도 항목으로 남는다")
|
||||
void aDifferentReasonIsADifferentEntry() {
|
||||
// given
|
||||
SuppressionEntry bounce = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null));
|
||||
|
||||
// when
|
||||
SuppressionEntry complaint = upsert(entry(SuppressionReason.COMPLAINT, NOW, null));
|
||||
|
||||
// then
|
||||
assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(1)))
|
||||
.containsExactlyInAnyOrder(bounce, complaint);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("만료됐거나 아직 시작하지 않은 수신 거부는 조회되지 않는다")
|
||||
void anEntryOutsideItsWindowIsNotActive() {
|
||||
// given
|
||||
upsert(entry(SuppressionReason.TEMPORARY_SUPPRESSION, NOW, NOW.plus(Duration.ofHours(1))));
|
||||
|
||||
// when
|
||||
List<SuppressionEntry> before = store().activeFor(TENANT, TARGET, NOW.minusSeconds(1));
|
||||
|
||||
// then
|
||||
assertThat(before).isEmpty();
|
||||
assertThat(store().activeFor(TENANT, TARGET, NOW.plus(Duration.ofHours(1)))).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 테넌트의 수신 거부는 조회되지도 삭제되지도 않는다")
|
||||
void anotherTenantNeitherSeesNorRemovesTheEntry() {
|
||||
// given
|
||||
SuppressionEntry stored = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null));
|
||||
|
||||
// when
|
||||
Optional<SuppressionEntry> removed =
|
||||
inTransaction(() -> store().remove(OTHER_TENANT, stored.id()));
|
||||
|
||||
// then
|
||||
assertThat(removed).isEmpty();
|
||||
assertThat(store().activeFor(OTHER_TENANT, TARGET, NOW.plusSeconds(1))).isEmpty();
|
||||
assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(1))).containsExactly(stored);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("삭제한 수신 거부는 돌려받고 더는 조회되지 않는다")
|
||||
void aRemovedEntryIsReturnedAndNoLongerActive() {
|
||||
// given
|
||||
SuppressionEntry stored = upsert(entry(SuppressionReason.HARD_BOUNCE, NOW, null));
|
||||
|
||||
// when
|
||||
Optional<SuppressionEntry> removed = inTransaction(() -> store().remove(TENANT, stored.id()));
|
||||
|
||||
// then
|
||||
assertThat(removed).contains(stored);
|
||||
assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(1))).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("같은 대상의 첫 수신 거부가 동시에 두 번 와도 둘 다 성공하고 항목은 하나다")
|
||||
void twoOverlappingFirstUpsertsBothSucceedAndLeaveOneEntry() {
|
||||
// given
|
||||
SuppressionEntry fromFirstWebhook = entry(SuppressionReason.HARD_BOUNCE, NOW, null);
|
||||
SuppressionEntry fromSecondWebhook =
|
||||
entry(SuppressionReason.HARD_BOUNCE, NOW.plusSeconds(5), null);
|
||||
|
||||
// when
|
||||
List<SuppressionEntry> results =
|
||||
OverlappingWrites.run(
|
||||
this::inTransaction,
|
||||
() -> store().upsert(fromFirstWebhook),
|
||||
() -> store().upsert(fromSecondWebhook));
|
||||
|
||||
// then
|
||||
assertThat(results.get(1).id())
|
||||
.as("both calls name the one stored entry")
|
||||
.isEqualTo(results.get(0).id());
|
||||
assertThat(store().activeFor(TENANT, TARGET, NOW.plusSeconds(10)))
|
||||
.as("the second webhook refreshed the entry rather than adding a duplicate")
|
||||
.containsExactly(results.get(1));
|
||||
}
|
||||
|
||||
private SuppressionEntry upsert(SuppressionEntry entry) {
|
||||
return inTransaction(() -> store().upsert(entry));
|
||||
}
|
||||
|
||||
private static SuppressionEntry entry(
|
||||
SuppressionReason reason, Instant effectiveAt, Instant expiresAt) {
|
||||
return new SuppressionEntry(
|
||||
new SuppressionId(UUID.randomUUID()),
|
||||
TENANT,
|
||||
SuppressionScope.CONTACT_POINT,
|
||||
reason,
|
||||
TARGET,
|
||||
Optional.empty(),
|
||||
effectiveAt,
|
||||
Optional.ofNullable(expiresAt),
|
||||
SuppressionSource.PROVIDER);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user