fix!: 재리뷰가 찾은 결함과 색인에서 빠졌던 발견 5건을 고친다

문제: 성숙도 리뷰 수정을 다시 읽은 재리뷰(Critical 0, 회귀 0)가
Important 27건·Minor 41건을 찾았다. 수정이 새로 만든 결함이 많았다.
@SystemInvoked가 권한 규칙의 탈출구가 됐고, 데모 계정 거부가 정확히
prod일 때만 걸렸고, outbox 순서 번호가 업그레이드 때 뒤로 갔고,
GraphQL union 아래 복잡도가 0이었고, 서블릿 오류 응답이 success:true로
나갔고, 호출자 deadline이 breaker를 열었다. 원래 리뷰 색인이 06 영역
발견 5건(06-10~14)을 빠뜨려 그동안 처리되지 않았다.

방법: 영역별 7묶음이 test-driven-development 절차로 실패 테스트를
먼저 쓰고 고쳤다. 결정은 재리뷰 README 4절에 적었다: 순서 번호는 V21이
기록한 전역 floor부터, 데모 계정은 local·test·demo 허용 목록,
@SystemInvoked bean은 기동 실패, complete 단계 실패는
IDEMPOTENCY_COMPLETION_UNKNOWN(결과 불명), 캐시 조건부 쓰기는 별도
SCRIPT lane, strict lane 정책은 build cache 입력, 끝나지 않는 재시도
행은 원인 코드·지표·PARKED 절차. 레지스트리가 선언만 하고 아무 코드도
내보내지 않던 redis.capability.* 지표 6개는 빼고 runbook을 실제
지표(redis.lane.*) 기준으로 고쳤다.

위험·한계: V21을 V22 없이 직접 고쳤다(어느 배포에도 아직 없음). 이
브랜치의 V21을 적용한 개발 DB는 다시 만들어야 한다. 서블릿 오류
디스패치를 보안 체인이 허용한다. 발행·저장소 포트 시그니처가 바뀌어
파생 서비스 코드가 깨진다. prod에서 fixture-로 시작하는 설정값은
기동을 막는다. httpclient failure-injection lane의 main 단계 중복
실행은 이전 결정대로 남겼다. 실제 CI runner 실행은 확인하지 못했다.

검증: ci, mainCheck, :integrationCheck, -p optional-platforms ci
integrationCheck performanceCheck, :performanceCheck, :releaseCheck
(-PgitRevision), verify-compose-profile-contracts(18 lane) 통과.
첫 실행의 실패 2건(FindSecBugs 1, sample 동시 생성 테스트의 v4 event
id)은 고친 뒤 ci·integrationCheck·mainCheck를 다시 돌려 통과했다.

Refs: docs/reviews/2026-11-03-rereview/README.md 3·4·6·7절
BREAKING CHANGE: outbox 발행 포트와 저장소 포트 시그니처, 순서 번호
첫 값(V21 floor 다음), 샘플 데모 계정 프로필 허용 목록, 새 오류 코드
IDEMPOTENCY_COMPLETION_UNKNOWN, prod의 fixture- 값 거부, 기동 rule은
static·의존 없음이어야 한다.
This commit is contained in:
DongHyeonka
2026-11-03 23:29:35 +09:00
parent 7ef8d0b4cb
commit bbe944bd3c
406 changed files with 13493 additions and 1656 deletions
+5 -4
View File
@@ -11,10 +11,11 @@ dependencies {
// The port owner's test fixtures: one hand-rolled fake per port, and the abstract port
// contracts (`*Contract`) that a fake and the real adapter both extend (AGENTS.md test rule 6,
// capability criterion 5). A use-case test that passes against a fake is passing against the
// behaviour the JPA adapters in persistence-fileserver are held to. Adapters reach them with
// `testImplementation testFixtures(...)`. FileserverException's error code is a shared-contract
// type; the contracts assert on it.
// capability criterion 5). Every store port persistence-fileserver implements has one, and so
// does the access policy (docs/testing/TESTING_STRATEGY.md 9.3), so a use-case test that passes
// against a fake is passing against the behaviour the JPA adapters are held to on PostgreSQL.
// Adapters reach them with `testImplementation testFixtures(...)`. FileserverException's error
// code is a shared-contract type; the contracts assert on it.
testFixturesImplementation project(':application-core')
// DirectTransactions records and injects faults around application-core's shared fake rather
// than being a second transaction port of its own.
@@ -1,5 +1,6 @@
package dev.caskeleton.application.fileserver.api.security;
import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor;
import dev.caskeleton.application.fileserver.api.metadata.FileOwner;
import java.util.Map;
import java.util.Objects;
@@ -45,4 +46,21 @@ public record FileAccessSubject(
public FileOwner asOwner() {
return new FileOwner(principalId, tenant());
}
/**
* Whether this caller created {@code file}, in this caller's tenant: the one ownership rule every
* {@link FileAccessPolicyPort} applies to an operation on an existing file (owner decision 14).
*
* <p>A file with no recorded owner predates ownership and belongs to nobody. A file created
* without a tenant is not owned by the same principal calling with one, and the other way round.
* Policies call this instead of comparing owners themselves, so the fake and every production
* policy cannot drift apart (review 2026-11-03 RR-07-06); {@code FileAccessPolicyPortContract}
* holds each of them to it.
*
* @param file the file the operation targets
* @return true when this caller owns it
*/
public boolean owns(FileDescriptor file) {
return file.owner().filter(asOwner()::equals).isPresent();
}
}
@@ -6,7 +6,9 @@ import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
* Returns committed capacity after content is physically gone.
*
* <p>Reclaim happens after the delete, never before: giving the quota back first would let a tenant
* over-allocate against space that has not actually been freed.
* over-allocate against space that has not actually been freed. The one other caller is a move to
* another namespace, which reclaims the file's bytes from the source in the same transaction that
* commits them to the target — the bytes stay counted, only their namespace changes.
*/
public interface QuotaReclaimPort {
@@ -4,21 +4,44 @@ import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.StorageNamespace;
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort;
import dev.caskeleton.application.fileserver.api.metadata.FileRecord;
import dev.caskeleton.application.fileserver.api.metadata.FileRecords;
import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation;
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort;
import dev.caskeleton.application.fileserver.api.security.FileOperation;
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
import dev.caskeleton.application.fileserver.port.in.MoveFileCommand;
import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase;
import dev.caskeleton.application.fileserver.upload.FileView;
import dev.caskeleton.application.fileserver.upload.UploadPolicies;
import dev.caskeleton.application.fileserver.upload.UploadPolicy;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import java.util.Objects;
import java.util.Optional;
/** Moves a readable file to another namespace that {@link TargetNamespacePolicy} opens. */
/**
* Moves a readable file to another namespace that {@link TargetNamespacePolicy} opens, and its
* bytes' quota with it.
*
* <p>Quota usage is booked per namespace, so a move that only relocated the record left the bytes
* counted where the file no longer is and uncounted where it now lives: the target could pass its
* limit through moves, the source carried the departed file forever, and deleting the moved file
* reclaimed from the target what the target never booked (review 2026-11-03 RR-01-05). A move
* across namespaces therefore does, in the one transaction that relocates the record, what an
* upload into the target and a delete from the source would: {@link
* dev.caskeleton.application.fileserver.quota.NamespaceQuota#requireRoom} against the target,
* reserve and commit the file's bytes there, and reclaim the same bytes from the source. A refused
* move changes nothing. A move within the namespace leaves the ledger alone.
*
* <p>Copy-then-delete was the other way to close it, and was not taken: a move would stop being
* atomic and would rewrite bytes the content key already addresses.
*/
@RequiresPermission("file:move")
@UseCaseCapability(
transactionMode = TransactionMode.WRITE,
@@ -30,17 +53,25 @@ public class MoveFileApplicationUseCase implements MoveFileUseCase {
private final FileMetadataPort metadataStore;
private final FileAccessPolicyPort accessPolicy;
private final UploadPolicy uploadPolicy;
private final TargetNamespacePolicy targetNamespaces;
private final FileQuotaPort quota;
private final QuotaReclaimPort reclaims;
private final TransactionPort transactions;
public MoveFileApplicationUseCase(
FileMetadataPort metadataStore,
FileAccessPolicyPort accessPolicy,
UploadPolicies policies,
TargetNamespacePolicy targetNamespaces,
FileQuotaPort quota,
QuotaReclaimPort reclaims,
TransactionPort transactions) {
this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore");
this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy");
this.accessPolicy = policies.access();
this.uploadPolicy = policies.upload();
this.targetNamespaces = Objects.requireNonNull(targetNamespaces, "targetNamespaces");
this.quota = Objects.requireNonNull(quota, "quota");
this.reclaims = Objects.requireNonNull(reclaims, "reclaims");
this.transactions = Objects.requireNonNull(transactions, "transactions");
}
@@ -57,7 +88,28 @@ public class MoveFileApplicationUseCase implements MoveFileUseCase {
return FileView.of(
transactions
.inWrite(
() -> metadataStore.relocate(fileId, record.version(), command.targetNamespace()))
() -> {
transferQuota(record, command.targetNamespace());
return metadataStore.relocate(
fileId, record.version(), command.targetNamespace());
})
.toDescriptor());
}
/** Books the file's bytes on {@code target} and takes them off the namespace it leaves. */
private void transferQuota(FileRecord record, StorageNamespace target) {
if (record.namespace().equals(target)) {
return;
}
long bytes = record.actualSize().orElseThrow(MoveFileApplicationUseCase::readyWithoutSize);
QuotaScope targetScope = QuotaScope.ofNamespace(target.value());
uploadPolicy.namespaceQuota().requireRoom(quota, targetScope, bytes);
QuotaReservation reservation = quota.reserve(targetScope, bytes, uploadPolicy.reservationTtl());
quota.commit(reservation, bytes);
reclaims.reclaim(QuotaScope.ofNamespace(record.namespace().value()), bytes);
}
private static IllegalStateException readyWithoutSize() {
return new IllegalStateException("READY record has no size");
}
}
@@ -17,6 +17,7 @@ import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
import dev.caskeleton.application.fileserver.testkit.DirectTransactions;
import dev.caskeleton.application.fileserver.testkit.FakeCleanupContentGateway;
import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService;
import dev.caskeleton.application.fileserver.testkit.FileserverFixtures;
import dev.caskeleton.application.fileserver.testkit.InMemoryCleanupQueue;
import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore;
@@ -40,7 +41,8 @@ class CleanupServiceTest {
private final FakeCleanupContentGateway content = new FakeCleanupContentGateway();
private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore();
private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore();
private final RecordingQuotaReclaimGateway quota = new RecordingQuotaReclaimGateway();
private final RecordingQuotaReclaimGateway quota =
new RecordingQuotaReclaimGateway(new FakeFileQuotaService());
private final DirectTransactions transactions = new DirectTransactions();
private final CleanupService cleanup =
@@ -35,6 +35,7 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryCleanupQueue;
import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore;
import dev.caskeleton.application.fileserver.testkit.InMemoryUploadSessionStore;
import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture;
import dev.caskeleton.application.fileserver.testkit.RecordingQuotaReclaimGateway;
import dev.caskeleton.application.fileserver.testkit.SequentialUploadIdentifierFactory;
import dev.caskeleton.application.fileserver.upload.FileView;
import dev.caskeleton.application.fileserver.upload.UploadPolicies;
@@ -83,8 +84,20 @@ class FileLifecycleUseCasesTest {
private final CopyFileApplicationUseCase copy =
copyUnder(UploadPolicy.standard(FileserverFixtures.NAMESPACE));
private final RecordingQuotaReclaimGateway reclaims = new RecordingQuotaReclaimGateway(quota);
private final MoveFileApplicationUseCase move =
new MoveFileApplicationUseCase(metadata, accessPolicy, TARGETS, transactions);
moveUnder(UploadPolicy.standard(FileserverFixtures.NAMESPACE));
private MoveFileApplicationUseCase moveUnder(UploadPolicy policy) {
return new MoveFileApplicationUseCase(
metadata,
new UploadPolicies(accessPolicy, OriginalFilenamePolicy.standard(), policy),
TARGETS,
quota,
reclaims,
transactions);
}
private CopyFileApplicationUseCase copyUnder(UploadPolicy policy) {
return new CopyFileApplicationUseCase(
@@ -449,6 +462,56 @@ class FileLifecycleUseCasesTest {
.containsExactly(FileserverErrorCode.ACCESS_DENIED, ready.namespace());
}
@Test
@DisplayName("이동은 파일의 바이트를 출발 namespace 사용량에서 대상 namespace 사용량으로 옮긴다")
void moveTransfersTheFilesBytesFromTheSourceNamespaceToTheTarget() {
// given
FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
QuotaScope source = QuotaScope.ofNamespace(ready.namespace().value());
QuotaScope target = QuotaScope.ofNamespace(TARGET.value());
quota.alreadyHolds(source, SIZE);
// when
move.handle(
new MoveFileCommand(
ready.fileId(), TARGET, Optional.empty(), FileserverFixtures.context()));
// then
assertThat(List.of(quota.usedBytes(source), quota.usedBytes(target))).containsExactly(0L, SIZE);
}
@Test
@DisplayName("대상 namespace 쿼터 상한을 넘기는 이동은 QUOTA_EXCEEDED로 거절되고 파일과 사용량은 그대로다")
void moveThatWouldTakeTheTargetNamespacePastItsQuotaIsRefused() {
// given
FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
QuotaScope source = QuotaScope.ofNamespace(ready.namespace().value());
QuotaScope target = QuotaScope.ofNamespace(TARGET.value());
quota.alreadyHolds(source, SIZE);
quota.alreadyHolds(target, 15);
MoveFileApplicationUseCase limited =
moveUnder(
UploadPolicy.standard(FileserverFixtures.NAMESPACE)
.withNamespaceQuota(NamespaceQuota.ofBytes(24)));
// when
Throwable failure =
catchThrowable(
() ->
limited.handle(
new MoveFileCommand(
ready.fileId(), TARGET, Optional.empty(), FileserverFixtures.context())));
// then
assertThat(
List.of(
codeOf(failure),
metadata.find(ready.fileId()).orElseThrow().namespace(),
quota.usedBytes(source),
quota.usedBytes(target)))
.containsExactly(FileserverErrorCode.QUOTA_EXCEEDED, ready.namespace(), SIZE, 15L);
}
private static Object codeOf(Throwable failure) {
if (failure == null) {
return "no failure";
@@ -11,6 +11,7 @@ import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft;
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
import dev.caskeleton.application.fileserver.testkit.DirectTransactions;
import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService;
import dev.caskeleton.application.fileserver.testkit.FakeQuotaCommitGateway;
import dev.caskeleton.application.fileserver.testkit.FakeReconciliationContentProbe;
import dev.caskeleton.application.fileserver.testkit.FileserverFixtures;
@@ -33,7 +34,8 @@ class FileReconciliationServiceTest {
private final FakeReconciliationContentProbe probe = new FakeReconciliationContentProbe();
private final InMemoryRecoveryQueue recovery = new InMemoryRecoveryQueue();
private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore();
private final FakeQuotaCommitGateway quota = new FakeQuotaCommitGateway();
private final FakeQuotaCommitGateway quota =
new FakeQuotaCommitGateway(new FakeFileQuotaService(), metadata);
private final FileReconciliationService service =
new DefaultFileReconciliationService(
@@ -0,0 +1,25 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort;
import dev.caskeleton.application.fileserver.api.security.FileAccessSubject;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
class FakeFileAccessPolicyContractTest extends FileAccessPolicyPortContract {
private final FakeFileAccessPolicy policy = new FakeFileAccessPolicy();
@Override
protected FileAccessPolicyPort policy() {
return policy;
}
@Override
protected FileAccessSubject permittedSubject(String principalId, Optional<String> tenant) {
return new FileAccessSubject(
principalId,
Set.of("uploader"),
tenant.map(value -> Map.of(FileAccessSubject.TENANT_ATTRIBUTE, value)).orElse(Map.of()));
}
}
@@ -0,0 +1,19 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort;
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
class InMemoryContentReferenceLedgerContractTest extends ContentReferenceLedgerPortContract {
private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore();
@Override
protected ContentReferenceLedgerPort ledger() {
return metadata;
}
@Override
protected FileMetadataPort metadata() {
return metadata;
}
}
@@ -0,0 +1,58 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.StorageNamespace;
import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort;
import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft;
import dev.caskeleton.application.fileserver.api.metadata.UploadSession;
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
import dev.caskeleton.application.fileserver.upload.QuotaCommitPort;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.UUID;
class InMemoryQuotaLedgerContractTest extends FileQuotaLedgerContract {
private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore();
private final FakeFileQuotaService ledger = new FakeFileQuotaService();
private final FakeQuotaCommitGateway commits = new FakeQuotaCommitGateway(ledger, metadata);
private final RecordingQuotaReclaimGateway reclaims = new RecordingQuotaReclaimGateway(ledger);
private Instant now = FileserverFixtures.NOW;
@Override
protected FileQuotaPort quota() {
return ledger;
}
@Override
protected QuotaCommitPort commits() {
return commits;
}
@Override
protected QuotaReclaimPort reclaims() {
return reclaims;
}
@Override
protected UploadSession uploadIn(StorageNamespace namespace) {
FileId fileId = FileId.of(UUID.randomUUID());
metadata.insert(
new FileRecordDraft(
fileId,
namespace,
"report.bin",
Optional.empty(),
OptionalLong.of(1_000),
FileserverFixtures.context().subject().asOwner()));
return FileserverFixtures.session(fileId, 1_000, 1_000);
}
@Override
protected void elapse(Duration duration) {
now = now.plus(duration);
ledger.advanceTo(now);
}
}
@@ -0,0 +1,20 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort;
import java.util.UUID;
class InMemoryRecoveryQueueContractTest extends RecoveryQueuePortContract {
private final InMemoryRecoveryQueue queue = new InMemoryRecoveryQueue();
@Override
protected RecoveryQueuePort queue() {
return queue;
}
@Override
protected FileId recordedFile() {
return FileId.of(UUID.randomUUID());
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort;
import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
class InMemoryStagingUploadLocatorContractTest extends StagingUploadLocatorPortContract {
private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore();
private Instant now = FileserverFixtures.NOW;
@Override
protected StagingUploadLocatorPort locator() {
return sessions;
}
@Override
protected UploadSessionPort sessions() {
return sessions;
}
@Override
protected FileId recordedFile() {
return FileId.of(UUID.randomUUID());
}
@Override
protected Instant now() {
return now;
}
@Override
protected void elapse(Duration duration) {
now = now.plus(duration);
sessions.advanceTo(now);
}
}
@@ -0,0 +1,34 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
class InMemoryUploadSessionStoreContractTest extends UploadSessionPortContract {
private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore();
private Instant now = FileserverFixtures.NOW;
@Override
protected UploadSessionPort sessions() {
return sessions;
}
@Override
protected FileId recordedFile() {
return FileId.of(UUID.randomUUID());
}
@Override
protected Instant now() {
return now;
}
@Override
protected void elapse(Duration duration) {
now = now.plus(duration);
sessions.advanceTo(now);
}
}
@@ -21,6 +21,7 @@ import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator;
import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand;
import dev.caskeleton.application.fileserver.testkit.DirectTransactions;
import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy;
import dev.caskeleton.application.fileserver.testkit.FakeFileQuotaService;
import dev.caskeleton.application.fileserver.testkit.FakeQuotaCommitGateway;
import dev.caskeleton.application.fileserver.testkit.FakeUploadContentGateway;
import dev.caskeleton.application.fileserver.testkit.FileserverFixtures;
@@ -43,7 +44,8 @@ class FinalizeUploadApplicationUseCaseTest {
private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore();
private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore();
private final FakeUploadContentGateway content = new FakeUploadContentGateway();
private final FakeQuotaCommitGateway quota = new FakeQuotaCommitGateway();
private final FakeQuotaCommitGateway quota =
new FakeQuotaCommitGateway(new FakeFileQuotaService(), metadata);
private final InMemoryCleanupQueue cleanup = new InMemoryCleanupQueue();
private final InMemoryRecoveryQueue recovery = new InMemoryRecoveryQueue();
private final FakeFileAccessPolicy accessPolicy = new FakeFileAccessPolicy();
@@ -0,0 +1,123 @@
package dev.caskeleton.application.fileserver.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort;
import dev.caskeleton.application.fileserver.api.ContentKey;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.FileState;
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
import dev.caskeleton.application.fileserver.api.metadata.FileRecord;
import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation;
import java.util.UUID;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What every {@link ContentReferenceLedgerPort} promises, run against the in-memory metadata store
* and the JPA ledger on real PostgreSQL (review 2026-11-03 RR-01-04).
*
* <p>A key is referenced while any record names it, in any state: an orphan scan that deleted the
* object of a record mid-delete would race the cleanup worker.
*/
public abstract class ContentReferenceLedgerPortContract {
protected abstract ContentReferenceLedgerPort ledger();
/** The metadata store the ledger answers from, to record files with. */
protected abstract FileMetadataPort metadata();
/** Runs one store call inside the caller transaction the adapter requires, and commits it. */
protected <T> T inTransaction(Supplier<T> work) {
return work.get();
}
@Test
@DisplayName("어느 레코드도 가리키지 않는 키는 참조되지 않는다")
void aKeyNoRecordNamesIsNotReferenced() {
// given
ContentKey key = newKey();
// when
boolean referenced = inTransaction(() -> ledger().isReferenced(key));
// then
assertThat(referenced).isFalse();
}
@Test
@DisplayName("공개된 레코드가 가리키는 키는 참조된다")
void aKeyAPublishedRecordNamesIsReferenced() {
// given
ContentKey key = newKey();
publish(key);
// when
boolean referenced = inTransaction(() -> ledger().isReferenced(key));
// then
assertThat(referenced).isTrue();
}
@Test
@DisplayName("지우는 중인 레코드가 가리키는 키도 참조된다")
void aKeyStaysReferencedWhileItsRecordIsBeingDeleted() {
// given
ContentKey key = newKey();
FileRecord ready = publish(key);
inTransaction(() -> metadata().markDeleting(ready.fileId(), ready.version()));
// when
boolean referenced = inTransaction(() -> ledger().isReferenced(key));
// then
assertThat(referenced).isTrue();
}
/** Walks a fresh record to READY under {@code key} through the edges an upload takes. */
private FileRecord publish(ContentKey key) {
FileId fileId = FileId.of(UUID.randomUUID());
return inTransaction(
() -> {
FileRecord created = metadata().insert(FileserverFixtures.draft(fileId, 10));
FileRecord uploading =
metadata()
.transition(
fileId,
created.version(),
FileState.CREATED,
FileState.UPLOADING,
FileRecordMutation.none());
FileRecord uploaded =
metadata()
.transition(
fileId,
uploading.version(),
FileState.UPLOADING,
FileState.UPLOADED,
FileRecordMutation.uploaded(10, FileserverFixtures.DIGEST));
FileRecord verifying =
metadata()
.transition(
fileId,
uploaded.version(),
FileState.UPLOADED,
FileState.VERIFYING,
FileRecordMutation.none());
return metadata()
.transition(
fileId,
verifying.version(),
FileState.VERIFYING,
FileState.READY,
FileRecordMutation.publishAt(
key, 10, FileserverFixtures.DIGEST, FileserverFixtures.NOW));
});
}
private static ContentKey newKey() {
String flat = UUID.randomUUID().toString().replace("-", "");
return ContentKey.of(flat.substring(0, 2) + '/' + flat.substring(2, 4) + '/' + flat);
}
}
@@ -18,7 +18,9 @@ import java.util.Set;
*
* <p>It keeps the one rule every production policy owes the port: an operation on an existing file
* is refused unless the caller created it, in the same tenant (owner decision 14). Without it a use
* case that stopped passing the file's descriptor would still pass every test.
* case that stopped passing the file's descriptor would still pass every test. The rule is {@link
* FileAccessSubject#owns}, the same call the production policy makes, and {@link
* FileAccessPolicyPortContract} holds both to it.
*/
public final class FakeFileAccessPolicy implements FileAccessPolicyPort {
@@ -42,8 +44,7 @@ public final class FakeFileAccessPolicy implements FileAccessPolicyPort {
"operation denied by policy",
FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false));
}
if (descriptor.isPresent()
&& !descriptor.get().owner().equals(Optional.of(subject.asOwner()))) {
if (descriptor.isPresent() && !subject.owns(descriptor.get())) {
throw new FileserverException(
"subject does not own the file",
FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false));
@@ -1,84 +1,115 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort;
import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation;
import dev.caskeleton.application.fileserver.api.metadata.QuotaReservationStatus;
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
* Hand-rolled quota service recording reservations, commits, and releases.
* The in-memory quota ledger: the fake of {@link FileQuotaPort}, and the ledger that {@link
* FakeQuotaCommitGateway} and {@link RecordingQuotaReclaimGateway} write, as the three JPA adapters
* share one reservation table.
*
* <p>It keeps the ledger the durable adapter keeps: a live reservation counts toward its scope's
* usage until it is committed (then the committed bytes count instead) or released (then nothing
* counts). That is what a configured namespace limit is compared against.
* <p>It keeps the rows the durable adapters keep and answers the way they do, which {@link
* FileQuotaLedgerContract} holds it to on the same cases as PostgreSQL: a live reservation counts
* until it expires, is committed (then the committed bytes count) or is released (then nothing
* counts); an expired or released reservation cannot be extended and a released one cannot be
* committed ({@code QUOTA_EXCEEDED}). Time is {@link FileserverFixtures#NOW} until {@link
* #advanceTo} moves it.
*
* <p>It also records what it was asked, for use-case tests that check which calls a flow made.
*/
public final class FakeFileQuotaService implements FileQuotaPort {
private final Map<UUID, Row> rows = new LinkedHashMap<>();
private final List<QuotaReservation> reserved = new ArrayList<>();
private final List<QuotaReservation> released = new ArrayList<>();
private final List<Long> committed = new ArrayList<>();
private final Map<UUID, Long> liveBytes = new HashMap<>();
private final Map<UUID, QuotaScope> scopes = new HashMap<>();
private final Map<QuotaScope, Long> committedUsage = new HashMap<>();
private Instant now = FileserverFixtures.NOW;
private long writes;
/** Moves the ledger's clock; reservations whose TTL ends by then stop counting. */
public void advanceTo(Instant instant) {
this.now = instant;
}
/** Books usage the scope already holds, as if earlier uploads had committed it. */
public void alreadyHolds(QuotaScope scope, long bytes) {
committedUsage.merge(scope, bytes, Long::sum);
Row row = newRow(scope, bytes, now);
row.commit(bytes, ++writes);
}
@Override
public QuotaReservation reserve(QuotaScope scope, long expectedBytes, Duration ttl) {
QuotaReservation reservation =
new QuotaReservation(
UUID.randomUUID(),
scope,
expectedBytes,
0,
FileserverFixtures.NOW.plus(ttl),
QuotaReservationStatus.RESERVED,
0);
requireNotNegative(expectedBytes, "expectedBytes");
Row row = newRow(scope, expectedBytes, now.plus(ttl));
QuotaReservation reservation = row.view();
reserved.add(reservation);
liveBytes.put(reservation.reservationId(), expectedBytes);
scopes.put(reservation.reservationId(), scope);
return reservation;
}
@Override
public void extend(QuotaReservation reservation, long additionalBytes) {
requireNotNegative(additionalBytes, "additionalBytes");
// The recorded reservation identity stays the same; the live total grows as the durable
// adapter's does.
reserved.add(reservation);
liveBytes.computeIfPresent(reservation.reservationId(), (id, bytes) -> bytes + additionalBytes);
Row row = rows.get(reservation.reservationId());
if (row == null || !row.isLiveAt(now)) {
throw quotaConflict("reservation is no longer extendable");
}
row.reservedBytes += additionalBytes;
row.updatedAt = ++writes;
}
@Override
public void commit(QuotaReservation reservation, long actualBytes) {
requireNotNegative(actualBytes, "actualBytes");
committed.add(actualBytes);
if (liveBytes.remove(reservation.reservationId()) != null) {
committedUsage.merge(scopes.get(reservation.reservationId()), actualBytes, Long::sum);
Row row = rows.get(reservation.reservationId());
// Expiry does not stop a commit: bytes that were written are durable usage whether or not the
// reservation outlived its TTL. Only a settled reservation is refused.
if (row == null || row.status != QuotaReservationStatus.RESERVED) {
throw quotaConflict("reservation is no longer committable");
}
row.commit(actualBytes, ++writes);
}
@Override
public void release(QuotaReservation reservation) {
released.add(reservation);
liveBytes.remove(reservation.reservationId());
Row row = rows.get(reservation.reservationId());
if (row != null && row.status == QuotaReservationStatus.RESERVED) {
row.release(++writes);
}
}
@Override
public long usedBytes(QuotaScope scope) {
long live =
liveBytes.entrySet().stream()
.filter(entry -> scope.equals(scopes.get(entry.getKey())))
.mapToLong(Map.Entry::getValue)
.sum();
return live + committedUsage.getOrDefault(scope, 0L);
long total = 0;
for (Row row : rows.values()) {
if (!row.scope.equals(scope)) {
continue;
}
if (row.isLiveAt(now)) {
total += row.reservedBytes;
} else if (row.status == QuotaReservationStatus.COMMITTED) {
total += row.committedBytes;
}
}
return total;
}
public List<QuotaScope> reservedScopes() {
@@ -96,4 +127,113 @@ public final class FakeFileQuotaService implements FileQuotaPort {
public List<Long> committedBytes() {
return List.copyOf(committed);
}
/**
* Settles an upload's share as {@code JpaQuotaCommit} does: the scope's oldest live reservation
* is committed, and with none left the bytes are still booked as committed usage.
*/
void settleOldestLive(QuotaScope scope, long actualBytes) {
requireNotNegative(actualBytes, "actualBytes");
Optional<Row> oldest = oldestLive(scope);
if (oldest.isPresent()) {
oldest.get().commit(actualBytes, ++writes);
} else if (actualBytes > 0) {
newRow(scope, actualBytes, now).commit(actualBytes, ++writes);
}
}
/** Releases the scope's oldest live reservation, as {@code JpaQuotaCommit.release} does. */
void releaseOldestLive(QuotaScope scope) {
oldestLive(scope).ifPresent(row -> row.release(++writes));
}
/**
* Gives committed bytes back as {@code JpaQuotaReclaim} does: newest committed rows first, never
* below zero, a remainder no row can absorb dropped. Live reservations are not touched.
*/
void reclaim(QuotaScope scope, long bytes) {
requireNotNegative(bytes, "bytes");
long outstanding = bytes;
List<Row> newestFirst =
rows.values().stream()
.filter(row -> row.scope.equals(scope))
.filter(row -> row.status == QuotaReservationStatus.COMMITTED)
.filter(row -> row.committedBytes > 0)
.sorted(Comparator.comparingLong((Row row) -> row.updatedAt).reversed())
.toList();
for (Row row : newestFirst) {
if (outstanding == 0) {
return;
}
long draw = Math.min(outstanding, row.committedBytes);
row.committedBytes -= draw;
row.updatedAt = ++writes;
outstanding -= draw;
}
}
private Optional<Row> oldestLive(QuotaScope scope) {
return rows.values().stream()
.filter(row -> row.scope.equals(scope))
.filter(row -> row.isLiveAt(now))
.findFirst();
}
private Row newRow(QuotaScope scope, long reservedBytes, Instant expiresAt) {
Row row = new Row(UUID.randomUUID(), scope, reservedBytes, expiresAt, ++writes);
rows.put(row.id, row);
return row;
}
private static void requireNotNegative(long bytes, String name) {
if (bytes < 0) {
throw new IllegalArgumentException(name + " must not be negative");
}
}
private static FileserverException quotaConflict(String message) {
return new FileserverException(
message, FileserverFailureContext.of(FileserverErrorCode.QUOTA_EXCEEDED, false));
}
/** One reservation row, in insertion order; {@code updatedAt} is a write counter. */
private static final class Row {
private final UUID id;
private final QuotaScope scope;
private final Instant expiresAt;
private long reservedBytes;
private long committedBytes;
private QuotaReservationStatus status = QuotaReservationStatus.RESERVED;
private long updatedAt;
private Row(UUID id, QuotaScope scope, long reservedBytes, Instant expiresAt, long createdAt) {
this.id = id;
this.scope = scope;
this.reservedBytes = reservedBytes;
this.expiresAt = expiresAt;
this.updatedAt = createdAt;
}
private boolean isLiveAt(Instant instant) {
return status == QuotaReservationStatus.RESERVED && expiresAt.isAfter(instant);
}
private void commit(long actualBytes, long write) {
status = QuotaReservationStatus.COMMITTED;
committedBytes = actualBytes;
reservedBytes = 0;
updatedAt = write;
}
private void release(long write) {
status = QuotaReservationStatus.RELEASED;
reservedBytes = 0;
updatedAt = write;
}
private QuotaReservation view() {
return new QuotaReservation(id, scope, reservedBytes, committedBytes, expiresAt, status, 0);
}
}
}
@@ -1,24 +1,57 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
import dev.caskeleton.application.fileserver.api.metadata.FileRecord;
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
import dev.caskeleton.application.fileserver.api.metadata.UploadSession;
import dev.caskeleton.application.fileserver.upload.QuotaCommitPort;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/** Hand-rolled quota gateway recording committed and released byte counts. */
/**
* The fake of {@link QuotaCommitPort}: settles an upload's share of its file's namespace on the
* in-memory ledger, as {@code JpaQuotaCommit} does on the reservation table, and records what it
* was asked. A session whose file has no record settles nothing. {@link FileQuotaLedgerContract}
* holds it to the JPA adapter's cases.
*/
public final class FakeQuotaCommitGateway implements QuotaCommitPort {
private final FakeFileQuotaService ledger;
private final FileMetadataPort metadata;
private final Map<UploadSession, Long> committed = new LinkedHashMap<>();
private final Map<UploadSession, Boolean> released = new LinkedHashMap<>();
/**
* A gateway over {@code ledger}, resolving each session's namespace from {@code metadata}.
*
* @param ledger the ledger the reservations live in
* @param metadata the records the sessions' files are found in
*/
public FakeQuotaCommitGateway(FakeFileQuotaService ledger, FileMetadataPort metadata) {
this.ledger = Objects.requireNonNull(ledger, "ledger");
this.metadata = Objects.requireNonNull(metadata, "metadata");
}
@Override
public void commit(UploadSession session, long actualBytes) {
if (actualBytes < 0) {
throw new IllegalArgumentException("actualBytes must not be negative");
}
committed.put(session, actualBytes);
metadata
.find(session.fileId())
.map(FakeQuotaCommitGateway::scopeOf)
.ifPresent(scope -> ledger.settleOldestLive(scope, actualBytes));
}
@Override
public void release(UploadSession session) {
released.put(session, Boolean.TRUE);
metadata
.find(session.fileId())
.map(FakeQuotaCommitGateway::scopeOf)
.ifPresent(ledger::releaseOldestLive);
}
public long committedBytes() {
@@ -32,4 +65,8 @@ public final class FakeQuotaCommitGateway implements QuotaCommitPort {
public boolean anyReleased() {
return !released.isEmpty();
}
private static QuotaScope scopeOf(FileRecord record) {
return QuotaScope.ofNamespace(record.namespace().value());
}
}
@@ -0,0 +1,175 @@
package dev.caskeleton.application.fileserver.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.FileState;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor;
import dev.caskeleton.application.fileserver.api.metadata.FileOwner;
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort;
import dev.caskeleton.application.fileserver.api.security.FileAccessSubject;
import dev.caskeleton.application.fileserver.api.security.FileOperation;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The ownership rule every {@link FileAccessPolicyPort} owes the port (owner decision 14), run
* against the fake and every production policy alike.
*
* <p>The rule itself is written once, {@link FileAccessSubject#owns(FileDescriptor)}; this contract
* is what keeps a policy from dropping or loosening its use of it. Use-case tests that prove a
* stranger cannot reach a file run on the fake, so they only mean something while the fake refuses
* exactly what the production policy refuses (review 2026-11-03 RR-07-06).
*
* <p>Roles are each policy's own business; a subclass hands the contract a subject its role rules
* let through every data-plane operation, and the cases vary only who owns the file.
*/
public abstract class FileAccessPolicyPortContract {
/** The policy under test. */
protected abstract FileAccessPolicyPort policy();
/**
* A subject the policy's role rules permit for every data-plane operation.
*
* @param principalId the caller
* @param tenant the caller's tenant, empty when the request was not tenant scoped
* @return that caller
*/
protected abstract FileAccessSubject permittedSubject(
String principalId, Optional<String> tenant);
@Test
@DisplayName("소유자는 자기 파일을 내려받고 지울 수 있다")
void theOwnerMayDownloadAndDeleteTheirFile() {
// given
FileAccessSubject owner = permittedSubject("user-1", Optional.of("tenant-1"));
Optional<FileDescriptor> file = fileOwnedBy("user-1", Optional.of("tenant-1"));
// when
Throwable refused =
catchThrowable(
() -> {
policy().authorize(FileOperation.DOWNLOAD, owner, file);
policy().authorize(FileOperation.DELETE, owner, file);
});
// then
assertThat(refused).isNull();
}
@Test
@DisplayName("같은 역할을 가진 다른 사용자의 파일은 ACCESS_DENIED다")
void anotherPrincipalsFileIsRefused() {
// given
FileAccessSubject stranger = permittedSubject("user-2", Optional.of("tenant-1"));
// when
Throwable refused =
catchThrowable(
() ->
policy()
.authorize(
FileOperation.DOWNLOAD,
stranger,
fileOwnedBy("user-1", Optional.of("tenant-1"))));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED);
}
@Test
@DisplayName("같은 사용자라도 다른 tenant에서 만든 파일은 ACCESS_DENIED다")
void theSamePrincipalInAnotherTenantIsRefused() {
// given
FileAccessSubject elsewhere = permittedSubject("user-1", Optional.of("tenant-2"));
// when
Throwable refused =
catchThrowable(
() ->
policy()
.authorize(
FileOperation.DOWNLOAD,
elsewhere,
fileOwnedBy("user-1", Optional.of("tenant-1"))));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED);
}
@Test
@DisplayName("tenant 없이 만든 파일은 tenant가 있는 같은 사용자에게도 ACCESS_DENIED다")
void aFileCreatedWithoutATenantIsRefusedToTheSamePrincipalWithOne() {
// given
FileAccessSubject scoped = permittedSubject("user-1", Optional.of("tenant-1"));
// when
Throwable refused =
catchThrowable(
() ->
policy()
.authorize(
FileOperation.DELETE, scoped, fileOwnedBy("user-1", Optional.empty())));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED);
}
@Test
@DisplayName("소유자가 기록되지 않은 파일은 누구에게도 ACCESS_DENIED다")
void aFileWithNoRecordedOwnerIsRefused() {
// given
FileAccessSubject caller = permittedSubject("user-1", Optional.empty());
// when
Throwable refused =
catchThrowable(
() -> policy().authorize(FileOperation.DOWNLOAD, caller, descriptor(Optional.empty())));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.ACCESS_DENIED);
}
@Test
@DisplayName("파일이 생기기 전의 연산은 소유자 없이 역할로만 판단한다")
void anOperationBeforeTheFileExistsIsDecidedWithoutAnOwner() {
// given
FileAccessSubject caller = permittedSubject("user-1", Optional.of("tenant-1"));
// when
Throwable refused =
catchThrowable(() -> policy().authorize(FileOperation.CREATE, caller, Optional.empty()));
// then
assertThat(refused).isNull();
}
private static Optional<FileDescriptor> fileOwnedBy(String principalId, Optional<String> tenant) {
return descriptor(Optional.of(new FileOwner(principalId, tenant)));
}
private static Optional<FileDescriptor> descriptor(Optional<FileOwner> owner) {
return Optional.of(
new FileDescriptor(
FileId.of(UUID.randomUUID()),
FileserverFixtures.NAMESPACE,
FileState.READY,
"report.bin",
"application/octet-stream",
10,
FileserverFixtures.DIGEST,
FileserverFixtures.NOW,
owner,
3));
}
private static Object codeOf(Throwable failure) {
return failure instanceof FileserverException refused ? refused.code() : failure;
}
}
@@ -0,0 +1,346 @@
package dev.caskeleton.application.fileserver.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.fileserver.api.StorageNamespace;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort;
import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation;
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
import dev.caskeleton.application.fileserver.api.metadata.UploadSession;
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
import dev.caskeleton.application.fileserver.upload.QuotaCommitPort;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The quota ledger, through all three ports that write it: {@link FileQuotaPort} reserves and
* settles reservations, {@link QuotaCommitPort} settles an upload's share, {@link QuotaReclaimPort}
* gives committed bytes back. They are one contract because they are one ledger — what a commit or
* a reclaim did is only visible as {@link FileQuotaPort#usedBytes}, the number a configured
* namespace limit is compared against (review 2026-11-03 RR-01-04).
*
* <p>Run against the in-memory ledger and the JPA adapters on real PostgreSQL. Every test works in
* namespaces of its own, so a subclass may share one store across tests.
*/
public abstract class FileQuotaLedgerContract {
private static final Duration TTL = Duration.ofHours(1);
protected abstract FileQuotaPort quota();
protected abstract QuotaCommitPort commits();
protected abstract QuotaReclaimPort reclaims();
/**
* An upload of a file recorded in {@code namespace}, as the finalize path holds one: the commit
* port settles against the namespace of the file the session belongs to.
*/
protected abstract UploadSession uploadIn(StorageNamespace namespace);
/** Lets {@code duration} pass on the clock the ledger reads. */
protected abstract void elapse(Duration duration);
/** Runs one ledger call inside the caller transaction the adapters require, and commits it. */
protected <T> T inTransaction(Supplier<T> work) {
return work.get();
}
@Test
@DisplayName("살아 있는 예약은 그 scope의 사용량에 들어간다")
void aLiveReservationCountsTowardItsScope() {
// given
QuotaScope scope = newScope();
// when
reserve(scope, 100);
// then
assertThat(usedBytes(scope)).isEqualTo(100);
}
@Test
@DisplayName("예약을 늘리면 늘린 만큼 사용량이 커진다")
void extendingAReservationGrowsTheUsage() {
// given
QuotaScope scope = newScope();
QuotaReservation reservation = reserve(scope, 100);
// when
run(() -> quota().extend(reservation, 50));
// then
assertThat(usedBytes(scope)).isEqualTo(150);
}
@Test
@DisplayName("확정하면 예약한 바이트 대신 실제 바이트가 사용량이 된다")
void committingCountsTheActualBytesInsteadOfTheReserved() {
// given
QuotaScope scope = newScope();
QuotaReservation reservation = reserve(scope, 100);
// when
run(() -> quota().commit(reservation, 60));
// then
assertThat(usedBytes(scope)).isEqualTo(60);
}
@Test
@DisplayName("해제한 예약은 사용량에서 빠진다")
void releasingAReservationGivesItBack() {
// given
QuotaScope scope = newScope();
QuotaReservation reservation = reserve(scope, 100);
// when
run(() -> quota().release(reservation));
// then
assertThat(usedBytes(scope)).isZero();
}
@Test
@DisplayName("만료된 예약은 사용량에서 빠진다")
void anExpiredReservationNoLongerCounts() {
// given
QuotaScope scope = newScope();
reserve(scope, 100);
// when
elapse(TTL.plusMinutes(1));
// then
assertThat(usedBytes(scope)).isZero();
}
@Test
@DisplayName("만료된 예약은 늘릴 수 없고 QUOTA_EXCEEDED로 거절된다")
void anExpiredReservationCannotBeExtended() {
// given
QuotaReservation reservation = reserve(newScope(), 100);
elapse(TTL.plusMinutes(1));
// when
Throwable refused = catchThrowable(() -> run(() -> quota().extend(reservation, 10)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.QUOTA_EXCEEDED);
}
@Test
@DisplayName("해제한 예약은 늘릴 수 없고 QUOTA_EXCEEDED로 거절된다")
void aReleasedReservationCannotBeExtended() {
// given
QuotaReservation reservation = reserve(newScope(), 100);
run(() -> quota().release(reservation));
// when
Throwable refused = catchThrowable(() -> run(() -> quota().extend(reservation, 10)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.QUOTA_EXCEEDED);
}
@Test
@DisplayName("해제한 예약은 확정할 수 없고 QUOTA_EXCEEDED로 거절된다")
void aReleasedReservationCannotBeCommitted() {
// given
QuotaReservation reservation = reserve(newScope(), 100);
run(() -> quota().release(reservation));
// when
Throwable refused = catchThrowable(() -> run(() -> quota().commit(reservation, 60)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.QUOTA_EXCEEDED);
}
/**
* Bytes that were written are durable usage whether or not the reservation outlived its TTL;
* dropping them because the reservation expired is how a ledger drifts below the truth.
*/
@Test
@DisplayName("만료됐지만 해제되지 않은 예약을 확정하면 실제 바이트가 사용량이 된다")
void committingAnExpiredReservationStillRecordsTheActualBytes() {
// given
QuotaScope scope = newScope();
QuotaReservation reservation = reserve(scope, 100);
elapse(TTL.plusMinutes(1));
// when
run(() -> quota().commit(reservation, 60));
// then
assertThat(usedBytes(scope)).isEqualTo(60);
}
@Test
@DisplayName("scope마다 사용량을 따로 센다")
void eachScopeIsCountedOnItsOwn() {
// given
QuotaScope scope = newScope();
reserve(scope, 100);
// when
reserve(newScope(), 30);
// then
assertThat(usedBytes(scope)).isEqualTo(100);
}
@Test
@DisplayName("음수 바이트 예약은 IllegalArgumentException으로 거절된다")
void aNegativeReservationIsRefused() {
// when
Throwable refused = catchThrowable(() -> reserve(newScope(), -1));
// then
assertThat(refused).isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("업로드 확정은 그 파일 namespace의 살아 있는 예약을 실제 바이트로 확정한다")
void settlingAnUploadCommitsItsNamespacesLiveReservation() {
// given
StorageNamespace namespace = newNamespace();
UploadSession upload = uploadIn(namespace);
reserve(scopeOf(namespace), 1_000);
// when
run(() -> commits().commit(upload, 600));
// then
assertThat(usedBytes(scopeOf(namespace))).isEqualTo(600);
}
@Test
@DisplayName("살아 있는 예약이 없어도 업로드 확정은 실제 바이트를 사용량으로 남긴다")
void settlingAnUploadWithNoLiveReservationStillRecordsTheUsage() {
// given
StorageNamespace namespace = newNamespace();
UploadSession upload = uploadIn(namespace);
// when
run(() -> commits().commit(upload, 450));
// then
assertThat(usedBytes(scopeOf(namespace))).isEqualTo(450);
}
@Test
@DisplayName("업로드 해제는 그 파일 namespace의 살아 있는 예약을 돌려준다")
void releasingAnUploadGivesItsNamespacesReservationBack() {
// given
StorageNamespace namespace = newNamespace();
UploadSession upload = uploadIn(namespace);
reserve(scopeOf(namespace), 2_000);
// when
run(() -> commits().release(upload));
// then
assertThat(usedBytes(scopeOf(namespace))).isZero();
}
@Test
@DisplayName("회수는 여러 확정분에 걸쳐 확정 사용량을 줄인다")
void reclaimingDrawsCommittedUsageDownAcrossCommits() {
// given
QuotaScope scope = newScope();
commit(scope, 300);
commit(scope, 700);
// when
run(() -> reclaims().reclaim(scope, 800));
// then
assertThat(usedBytes(scope)).isEqualTo(200);
}
@Test
@DisplayName("기록보다 많이 회수하면 사용량은 0에서 멈춘다")
void reclaimingMoreThanIsRecordedStopsAtZero() {
// given
QuotaScope scope = newScope();
commit(scope, 100);
// when
run(() -> reclaims().reclaim(scope, 5_000));
// then
assertThat(usedBytes(scope)).isZero();
}
@Test
@DisplayName("회수는 살아 있는 예약과 다른 scope를 건드리지 않는다")
void reclaimingLeavesLiveReservationsAndOtherScopesAlone() {
// given
QuotaScope scope = newScope();
QuotaScope other = newScope();
reserve(scope, 100);
commit(scope, 50);
commit(other, 70);
// when
run(() -> reclaims().reclaim(scope, 500));
// then
assertThat(List.of(usedBytes(scope), usedBytes(other))).containsExactly(100L, 70L);
}
@Test
@DisplayName("음수 바이트 회수는 IllegalArgumentException으로 거절된다")
void aNegativeReclaimIsRefused() {
// when
Throwable refused = catchThrowable(() -> run(() -> reclaims().reclaim(newScope(), -1)));
// then
assertThat(refused).isInstanceOf(IllegalArgumentException.class);
}
private QuotaReservation reserve(QuotaScope scope, long bytes) {
return inTransaction(() -> quota().reserve(scope, bytes, TTL));
}
private void commit(QuotaScope scope, long bytes) {
QuotaReservation reservation = reserve(scope, bytes);
run(() -> quota().commit(reservation, bytes));
}
private long usedBytes(QuotaScope scope) {
return inTransaction(() -> quota().usedBytes(scope));
}
private void run(Runnable work) {
inTransaction(
() -> {
work.run();
return null;
});
}
private static StorageNamespace newNamespace() {
return StorageNamespace.of("q-" + UUID.randomUUID().toString().substring(0, 12));
}
private static QuotaScope newScope() {
return scopeOf(newNamespace());
}
private static QuotaScope scopeOf(StorageNamespace namespace) {
return QuotaScope.ofNamespace(namespace.value());
}
private static Object codeOf(Throwable failure) {
return failure instanceof FileserverException refused ? refused.code() : failure;
}
}
@@ -1,5 +1,7 @@
package dev.caskeleton.application.fileserver.testkit;
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort;
import dev.caskeleton.application.fileserver.api.ContentKey;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.FileState;
import dev.caskeleton.application.fileserver.api.StorageNamespace;
@@ -25,8 +27,13 @@ import java.util.concurrent.atomic.AtomicInteger;
* <p>Application tests must observe identical conflict behaviour, so this fake enforces the
* expected state and version rather than accepting any write. It is held to {@link
* FileMetadataPortContract}, the contract the JPA adapter passes against PostgreSQL.
*
* <p>Also answers {@link ContentReferenceLedgerPort} from the same records, as the JPA ledger reads
* the file table: a key is referenced while a record in any state names it ({@link
* ContentReferenceLedgerPortContract}).
*/
public final class InMemoryFileMetadataStore implements FileMetadataPort {
public final class InMemoryFileMetadataStore
implements FileMetadataPort, ContentReferenceLedgerPort {
private final Map<FileId, FileRecord> records = new LinkedHashMap<>();
private final AtomicInteger transitionFailuresToInject = new AtomicInteger();
@@ -70,6 +77,12 @@ public final class InMemoryFileMetadataStore implements FileMetadataPort {
return record;
}
@Override
public boolean isReferenced(ContentKey key) {
return records.values().stream()
.anyMatch(record -> record.contentKey().filter(key::equals).isPresent());
}
@Override
public Optional<FileRecord> find(FileId fileId) {
return Optional.ofNullable(records.get(fileId));
@@ -8,7 +8,12 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Hand-rolled recovery queue that records every escalation reason. */
/**
* Hand-rolled recovery queue that records every escalation reason.
*
* <p>Answers as the JPA queue does ({@link RecoveryQueuePortContract}): one open entry per file,
* oldest first, resolved entries out of the pending list and raisable again.
*/
public final class InMemoryRecoveryQueue implements RecoveryQueuePort {
private final Map<FileId, String> pending = new LinkedHashMap<>();
@@ -21,6 +26,9 @@ public final class InMemoryRecoveryQueue implements RecoveryQueuePort {
@Override
public List<FileId> pending(int limit) {
if (limit < 1) {
throw new IllegalArgumentException("limit must be positive");
}
return List.copyOf(
new ArrayList<>(pending.keySet()).subList(0, Math.min(limit, pending.size())));
}
@@ -12,7 +12,7 @@ import dev.caskeleton.application.fileserver.api.metadata.WriterLease;
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -28,6 +28,11 @@ import java.util.UUID;
*
* <p>Also answers {@link StagingUploadLocatorPort} from the same sessions, as the JPA locator reads
* the session table: the newest session recorded for a file.
*
* <p>{@link UploadSessionPortContract} and {@link StagingUploadLocatorPortContract} hold it to the
* JPA store's cases on PostgreSQL, including the two that read time: no lease on an upload past its
* expiry, and no offset commit once the writer's lease has lapsed ({@link #advanceTo} moves the
* store's clock).
*/
public final class InMemoryUploadSessionStore
implements UploadSessionPort, StagingUploadLocatorPort {
@@ -107,7 +112,8 @@ public final class InMemoryUploadSessionStore
UploadSession current = require(uploadId);
boolean leaseFree =
current.leaseUntil().isEmpty() || !current.leaseUntil().get().isAfter(clockNow);
if (current.terminal() || current.version() != expectedVersion || !leaseFree) {
boolean uploadOpen = current.expiresAt().isAfter(clockNow);
if (current.terminal() || current.version() != expectedVersion || !leaseFree || !uploadOpen) {
throw new FileserverException(
"writer lease is held by another owner",
FileserverFailureContext.forUpload(
@@ -156,7 +162,13 @@ public final class InMemoryUploadSessionStore
UploadId uploadId, WriterLease lease, long expectedOffset, long committedOffset) {
UploadSession current = require(uploadId);
boolean tokenMatches = current.leaseToken().map(lease.token()::equals).orElse(false);
if (current.terminal() || !tokenMatches || current.committedOffset() != expectedOffset) {
// The JPA statement reads its own clock here, not the caller's: a writer whose lease lapsed
// cannot advance the offset even when nobody has taken the lease over yet.
boolean stillHeld = current.leaseUntil().map(now::isBefore).orElse(false);
if (current.terminal()
|| !tokenMatches
|| !stillHeld
|| current.committedOffset() != expectedOffset) {
throw new FileserverException(
"offset commit rejected",
FileserverFailureContext.forOffset(
@@ -222,13 +234,13 @@ public final class InMemoryUploadSessionStore
@Override
public List<UploadSession> findExpired(Instant cutoff, int limit) {
List<UploadSession> expired = new ArrayList<>();
for (UploadSession session : sessions.values()) {
if (!session.terminal() && session.isExpiredAt(cutoff) && expired.size() < limit) {
expired.add(session);
}
}
return List.copyOf(expired);
// Strictly before the cutoff and earliest expiry first, as the JPA query reads them.
return sessions.values().stream()
.filter(session -> !session.terminal())
.filter(session -> session.expiresAt().isBefore(cutoff))
.sorted(Comparator.comparing(UploadSession::expiresAt))
.limit(limit)
.toList();
}
private UploadSession require(UploadId uploadId) {
@@ -4,12 +4,28 @@ import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/** Records every reclaim so a test can prove capacity is returned exactly once. */
/**
* The fake of {@link QuotaReclaimPort}: gives committed bytes back on the in-memory ledger as
* {@code JpaQuotaReclaim} does (newest first, floor zero), and records every reclaim so a test can
* prove capacity is returned exactly once. {@link FileQuotaLedgerContract} holds it to the JPA
* adapter's cases.
*/
public final class RecordingQuotaReclaimGateway implements QuotaReclaimPort {
private final FakeFileQuotaService ledger;
private final List<Long> reclaimed = new ArrayList<>();
/**
* A gateway over {@code ledger}.
*
* @param ledger the ledger the committed usage lives in
*/
public RecordingQuotaReclaimGateway(FakeFileQuotaService ledger) {
this.ledger = Objects.requireNonNull(ledger, "ledger");
}
public List<Long> reclaimed() {
return List.copyOf(reclaimed);
}
@@ -20,6 +36,7 @@ public final class RecordingQuotaReclaimGateway implements QuotaReclaimPort {
@Override
public void reclaim(QuotaScope scope, long bytes) {
ledger.reclaim(scope, bytes);
reclaimed.add(bytes);
}
}
@@ -0,0 +1,137 @@
package dev.caskeleton.application.fileserver.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.recovery.ReconciliationStatus;
import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort;
import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What every {@link RecoveryQueuePort} promises, run against the in-memory queue and the JPA queue
* on real PostgreSQL (review 2026-11-03 RR-01-04).
*
* <p>An entry is a request for an operator's decision: one open entry per file however often it is
* reported, gone from the pending list once resolved, and raisable again afterwards.
*/
public abstract class RecoveryQueuePortContract {
/** The queue under test, empty at the start of each test. */
protected abstract RecoveryQueuePort queue();
/** A file that has a record, which an entry may name. */
protected abstract FileId recordedFile();
/**
* Lets {@code duration} pass on the clock the queue stamps entries with. The pending list is
* oldest first; a store that orders by insertion keeps the default.
*/
protected void elapse(Duration duration) {}
/** Runs one queue call inside the caller transaction the adapter requires, and commits it. */
protected <T> T inTransaction(Supplier<T> work) {
return work.get();
}
@Test
@DisplayName("올린 파일은 대기 목록에 있다")
void anEnqueuedFileIsPending() {
// given
FileId file = recordedFile();
// when
run(() -> queue().enqueue(file, "READY_DIGEST_MISMATCH"));
// then
assertThat(pending(10)).containsExactly(file);
}
@Test
@DisplayName("같은 파일을 두 번 올려도 대기 항목은 하나다")
void theSameFileReportedTwiceIsPendingOnce() {
// given
FileId file = recordedFile();
run(() -> queue().enqueue(file, "READY_DIGEST_MISMATCH"));
// when
run(() -> queue().enqueue(file, "READY_SIZE_MISMATCH"));
// then
assertThat(pending(10)).containsExactly(file);
}
@Test
@DisplayName("처리한 파일은 대기 목록에서 빠진다")
void aResolvedFileLeavesThePendingList() {
// given
FileId file = recordedFile();
run(() -> queue().enqueue(file, "PUBLISH_EVIDENCE_INCOMPLETE"));
// when
run(() -> queue().resolve(file, ReconciliationStatus.QUARANTINE_REQUIRED));
// then
assertThat(pending(10)).isEmpty();
}
@Test
@DisplayName("처리한 파일도 나중에 다시 올릴 수 있다")
void aResolvedFileCanBeRaisedAgain() {
// given
FileId file = recordedFile();
run(() -> queue().enqueue(file, "FIRST"));
run(() -> queue().resolve(file, ReconciliationStatus.UNRESOLVED));
// when
run(() -> queue().enqueue(file, "SECOND"));
// then
assertThat(pending(10)).containsExactly(file);
}
@Test
@DisplayName("대기 목록은 먼저 올린 파일부터 한도만큼 준다")
void thePendingListIsOldestFirstUpToTheLimit() {
// given
FileId first = recordedFile();
FileId second = recordedFile();
FileId third = recordedFile();
for (FileId file : List.of(first, second, third)) {
run(() -> queue().enqueue(file, "UNSETTLED"));
elapse(Duration.ofSeconds(1));
}
// when
List<FileId> pending = pending(2);
// then
assertThat(pending).containsExactly(first, second);
}
@Test
@DisplayName("한도가 1보다 작으면 IllegalArgumentException으로 거절된다")
void aLimitBelowOneIsRefused() {
// when
Throwable refused = catchThrowable(() -> pending(0));
// then
assertThat(refused).isInstanceOf(IllegalArgumentException.class);
}
private List<FileId> pending(int limit) {
return inTransaction(() -> queue().pending(limit));
}
private void run(Runnable work) {
inTransaction(
() -> {
work.run();
return null;
});
}
}
@@ -0,0 +1,92 @@
package dev.caskeleton.application.fileserver.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.UploadId;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What every {@link StagingUploadLocatorPort} promises, run against the in-memory session store and
* the JPA locator on real PostgreSQL (review 2026-11-03 RR-01-04).
*
* <p>Only the newest upload of a file is returned: an older one names a staging object that has
* since been reclaimed, and treating it as live evidence would tell reconciliation the upload is
* resumable when it is not.
*/
public abstract class StagingUploadLocatorPortContract {
protected abstract StagingUploadLocatorPort locator();
/** The session store the locator reads, to record uploads with. */
protected abstract UploadSessionPort sessions();
/** A file that has a record, which an upload may belong to. */
protected abstract FileId recordedFile();
/** The instant the store reads as now. */
protected abstract Instant now();
/** Lets {@code duration} pass on the clock the store stamps sessions with. */
protected abstract void elapse(Duration duration);
/** Runs one store call inside the caller transaction the adapter requires, and commits it. */
protected <T> T inTransaction(Supplier<T> work) {
return work.get();
}
@Test
@DisplayName("업로드가 없던 파일은 아무것도 찾지 않는다")
void aFileThatWasNeverStagedLocatesNothing() {
// given
FileId file = recordedFile();
// when
Optional<UploadId> located = inTransaction(() -> locator().locate(file));
// then
assertThat(located).isEmpty();
}
@Test
@DisplayName("업로드가 여럿인 파일은 가장 최근 업로드를 찾는다")
void aFileStagedTwiceLocatesItsNewestUpload() {
// given
FileId file = recordedFile();
stage(file);
elapse(Duration.ofSeconds(1));
UploadId newest = stage(file);
// when
Optional<UploadId> located = inTransaction(() -> locator().locate(file));
// then
assertThat(located).contains(newest);
}
private UploadId stage(FileId file) {
UploadId uploadId = UploadId.of(UUID.randomUUID());
inTransaction(
() ->
sessions()
.create(
new UploadSessionDraft(
uploadId,
file,
UploadMode.SINGLE_SHOT,
OptionalLong.of(100),
now().plus(Duration.ofHours(1)))));
return uploadId;
}
}
@@ -0,0 +1,367 @@
package dev.caskeleton.application.fileserver.testkit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.fileserver.api.FileId;
import dev.caskeleton.application.fileserver.api.UploadId;
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
import dev.caskeleton.application.fileserver.api.error.FileserverException;
import dev.caskeleton.application.fileserver.api.metadata.UploadSession;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft;
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
import dev.caskeleton.application.fileserver.api.metadata.WriterLease;
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What every {@link UploadSessionPort} promises, run against the in-memory store and the JPA store
* on real PostgreSQL (review 2026-11-03 RR-01-04).
*
* <p>The writer lease is the only thing that keeps two instances from appending to one upload, so
* the cases are its rules: who may take a lease, who may renew it, who may advance the offset, and
* when an upload stops being writable at all.
*/
public abstract class UploadSessionPortContract {
private static final Duration LEASE = Duration.ofMinutes(1);
private static final Duration UPLOAD_LIFETIME = Duration.ofHours(1);
/** The store under test, holding no session at the start of each test. */
protected abstract UploadSessionPort sessions();
/** A file that has a record, which an upload may belong to. */
protected abstract FileId recordedFile();
/** The instant the store reads as now. */
protected abstract Instant now();
/** Lets {@code duration} pass on the clock the store reads. */
protected abstract void elapse(Duration duration);
/** Runs one store call inside the caller transaction the adapter requires, and commits it. */
protected <T> T inTransaction(Supplier<T> work) {
return work.get();
}
@Test
@DisplayName("새 업로드는 offset 0, lease 없음, 열린 상태로 다시 읽힌다")
void aCreatedUploadIsReadBackOpenAtOffsetZeroWithNoLease() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
// when
UploadSession found = find(uploadId);
// then
assertThat(List.of(found.committedOffset(), found.leaseToken().isPresent(), found.terminal()))
.containsExactly(0L, false, false);
}
@Test
@DisplayName("다른 writer가 lease를 쥐고 있으면 lease를 주지 않는다")
void aLeaseIsRefusedWhileAnotherWriterHoldsIt() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
acquire(uploadId, "node-a");
// when
Throwable refused = catchThrowable(() -> acquire(uploadId, "node-b"));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("만료된 lease는 다른 writer가 넘겨받는다")
void anExpiredLeaseIsTakenOverByAnotherWriter() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
acquire(uploadId, "node-a");
elapse(LEASE.plusSeconds(1));
// when
WriterLease taken = acquire(uploadId, "node-b");
// then
assertThat(find(uploadId).leaseToken()).contains(taken.token());
}
@Test
@DisplayName("기대한 버전이 지난 것이면 lease를 주지 않는다")
void aLeaseIsRefusedOnAStaleVersion() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
long stale = find(uploadId).version();
WriterLease first = acquire(uploadId, "node-a");
inTransaction(
() -> {
sessions().releaseLease(uploadId, first);
return null;
});
// when
Throwable refused =
catchThrowable(
() ->
inTransaction(
() -> sessions().acquireLease(uploadId, "node-b", now(), LEASE, stale)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("업로드 기한이 지나면 lease를 주지 않는다")
void aLeaseIsRefusedOnceTheUploadHasExpired() {
// given
UploadId uploadId = create(Duration.ofMinutes(5));
elapse(Duration.ofMinutes(6));
// when
Throwable refused = catchThrowable(() -> acquire(uploadId, "node-a"));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("갱신한 lease는 처음 만료 시각이 지나도 다른 writer에게 넘어가지 않는다")
void aRenewedLeaseOutlivesItsFirstExpiry() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease lease = acquire(uploadId, "node-a");
elapse(LEASE.dividedBy(2));
inTransaction(() -> sessions().renewLease(lease, now(), LEASE));
elapse(LEASE.dividedBy(2).plusSeconds(1));
// when
Throwable refused = catchThrowable(() -> acquire(uploadId, "node-b"));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("이미 만료된 lease는 갱신하지 않는다")
void aLapsedLeaseCannotBeRenewed() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease lease = acquire(uploadId, "node-a");
elapse(LEASE.plusSeconds(1));
// when
Throwable refused =
catchThrowable(() -> inTransaction(() -> sessions().renewLease(lease, now(), LEASE)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("lease를 쥔 writer는 기대한 offset에서 offset을 올린다")
void theLeaseHolderAdvancesTheOffsetFromTheExpectedOne() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease lease = acquire(uploadId, "node-a");
// when
UploadSession advanced = inTransaction(() -> sessions().commitOffset(uploadId, lease, 0, 40));
// then
assertThat(advanced.committedOffset()).isEqualTo(40);
}
@Test
@DisplayName("기대한 offset이 다르면 offset을 올리지 않는다")
void anOffsetCommitFromTheWrongOffsetIsRefused() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease lease = acquire(uploadId, "node-a");
// when
Throwable refused =
catchThrowable(() -> inTransaction(() -> sessions().commitOffset(uploadId, lease, 10, 40)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("lease를 빼앗긴 writer는 offset을 올리지 못한다")
void aWriterWhoseLeaseWasTakenOverCannotAdvanceTheOffset() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease stale = acquire(uploadId, "node-a");
elapse(LEASE.plusSeconds(1));
acquire(uploadId, "node-b");
// when
Throwable refused =
catchThrowable(() -> inTransaction(() -> sessions().commitOffset(uploadId, stale, 0, 40)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("lease가 만료된 writer는 아무도 넘겨받지 않았어도 offset을 올리지 못한다")
void aWriterWhoseLeaseLapsedCannotAdvanceTheOffset() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease lease = acquire(uploadId, "node-a");
elapse(LEASE.plusSeconds(1));
// when
Throwable refused =
catchThrowable(() -> inTransaction(() -> sessions().commitOffset(uploadId, lease, 0, 40)));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("다른 writer의 토큰으로 해제해도 쥐고 있는 lease는 남는다")
void releasingWithAnotherWritersTokenLeavesTheLeaseHeld() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
WriterLease held = acquire(uploadId, "node-a");
WriterLease other = new WriterLease(uploadId, "node-b", UUID.randomUUID(), now(), 0);
// when
inTransaction(
() -> {
sessions().releaseLease(uploadId, other);
return null;
});
// then
assertThat(find(uploadId).leaseToken()).contains(held.token());
}
@Test
@DisplayName("업로드를 끝내는 호출은 처음 한 번만 끝냈다고 답한다")
void terminatingAnUploadAnswersTrueOnlyTheFirstTime() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
boolean first = inTransaction(() -> sessions().terminate(uploadId));
// when
boolean second = inTransaction(() -> sessions().terminate(uploadId));
// then
assertThat(List.of(first, second)).containsExactly(true, false);
}
@Test
@DisplayName("끝난 업로드에는 lease를 주지 않는다")
void aTerminatedUploadRefusesANewLease() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
inTransaction(() -> sessions().terminate(uploadId));
// when
Throwable refused = catchThrowable(() -> acquire(uploadId, "node-a"));
// then
assertThat(codeOf(refused)).isEqualTo(FileserverErrorCode.CONCURRENT_MODIFICATION);
}
@Test
@DisplayName("끝났지만 writer가 아직 lease를 쥔 업로드는 정리 대상으로 잡지 않는다")
void aTerminatedUploadWhoseWriterStillHoldsTheLeaseIsNotClaimedForCleanup() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
acquire(uploadId, "node-a");
inTransaction(() -> sessions().terminate(uploadId));
// when
boolean claimed = inTransaction(() -> sessions().claimForCleanup(uploadId, now()));
// then
assertThat(claimed).isFalse();
}
@Test
@DisplayName("끝났고 lease가 만료된 업로드는 정리 대상으로 잡힌다")
void aTerminatedUploadWithALapsedLeaseIsClaimedForCleanup() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
acquire(uploadId, "node-a");
inTransaction(() -> sessions().terminate(uploadId));
elapse(LEASE.plusSeconds(1));
// when
boolean claimed = inTransaction(() -> sessions().claimForCleanup(uploadId, now()));
// then
assertThat(claimed).isTrue();
}
@Test
@DisplayName("열린 업로드는 정리 대상으로 잡지 않는다")
void anOpenUploadIsNotClaimedForCleanup() {
// given
UploadId uploadId = create(UPLOAD_LIFETIME);
// when
boolean claimed = inTransaction(() -> sessions().claimForCleanup(uploadId, now()));
// then
assertThat(claimed).isFalse();
}
@Test
@DisplayName("기한이 지난 열린 업로드만 기한이 이른 것부터 찾는다")
void expiredOpenUploadsAreFoundEarliestExpiryFirst() {
// given
UploadId later = create(Duration.ofMinutes(50));
UploadId earlier = create(Duration.ofMinutes(20));
create(Duration.ofHours(3));
UploadId ended = create(Duration.ofMinutes(10));
inTransaction(() -> sessions().terminate(ended));
Instant cutoff = now().plus(Duration.ofHours(1));
// when
List<UploadSession> expired = inTransaction(() -> sessions().findExpired(cutoff, 10));
// then
assertThat(expired).extracting(UploadSession::uploadId).containsExactly(earlier, later);
}
private UploadId create(Duration lifetime) {
UploadId uploadId = UploadId.of(UUID.randomUUID());
FileId file = recordedFile();
inTransaction(
() ->
sessions()
.create(
new UploadSessionDraft(
uploadId,
file,
UploadMode.RESUMABLE,
OptionalLong.of(100),
now().plus(lifetime))));
return uploadId;
}
private UploadSession find(UploadId uploadId) {
return inTransaction(() -> sessions().find(uploadId)).orElseThrow();
}
private WriterLease acquire(UploadId uploadId, String owner) {
long version = find(uploadId).version();
return inTransaction(() -> sessions().acquireLease(uploadId, owner, now(), LEASE, version));
}
private static Object codeOf(Throwable failure) {
return failure instanceof FileserverException refused ? refused.code() : failure;
}
}