fix!: 성숙도 리뷰의 High·P1 결함 19건을 고친다
문제: 2026-11-01 성숙도 리뷰에서 High 21건·P1 25건이 나왔다. 결과를 모르는 일을 "확실함"으로 기록했다(발송 중 죽은 알림 재발송, 커밋 중 끊긴 쓰기를 재시도 가능으로 응답, 재시도 가능한 거부를 DEAD로). 중복을 DB가 아니라 코드 순서로 막았다(정산 job, 포스터 제목). 짝 프론트와 wire 계약이 달랐고(처리 중 409, Envelope null), JWT audience 검증이 기본으로 꺼져 있었고, 트레이스가 나가지 않았고, CI가 strict lane 14개를 한 번도 돌리지 않았다. 방법: 발견마다 실패하는 테스트를 먼저 쓰고 고쳤다. 주요 선택: - 알림 attempt는 처음부터 "시작 여부 모름"으로 쓴다(호출 직전 갱신은 쓰기가 하나 늘어 버림). - 정산 job claim은 lease·fence를 갱신하는 UPDATE 한 문장(처리 전체를 트랜잭션으로 감싸는 안은 외부 호출 동안 잠금을 잡아 버림). - 커밋 단계 연결 끊김은 DB_COMPLETION_UNKNOWN(재시도 불가). - 처리 중 409는 retryable=true + Retry-After: 2, Envelope null 필드는 web Jackson mixin으로 생략(shared-contract는 stdlib only). - 트레이싱은 자체 Tracer를 지우고 Boot 4 tracing·OTLP로. - strict lane을 단계에 연결하고 verifyStrictLaneStages가 고아를 막는다. 발견별 RED·GREEN·버린 대안은 리뷰 README 13절 표에 있다. 위험·한계: JWT 모드는 APP_SECURITY_JWT_AUDIENCE가 없으면 기동하지 않는다. 짝 프론트는 409 retryable과 Envelope 키 규칙을 맞춰야 한다. 이 커밋 시점에는 MinIO 공식 이미지가 사라져 MinIO 2 lane이 실패한다 (다음 커밋에서 대체 이미지로 해결). 검증: ci 통과. mainCheck·integrationCheck는 MinIO 2 lane만 실패(이미지 pull 거부). -p optional-platforms ci integrationCheck, performanceCheck, releaseCheck(-PgitRevision) 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 2·13절 BREAKING CHANGE: JWT 모드에서 APP_SECURITY_JWT_AUDIENCE가 필수가 되고 role은 audience client와 realm 것만 읽는다. IDEMPOTENT_IN_FLIGHT가 retryable=true, Retry-After: 2로 바뀌고 Envelope는 null 필드를 보내지 않는다.
This commit is contained in:
+99
-50
@@ -7,10 +7,13 @@ import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.FileState;
|
||||
import dev.caskeleton.application.fileserver.api.content.StoredContent;
|
||||
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.FileRecordDraft;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation;
|
||||
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.api.security.OriginalFilenamePolicy;
|
||||
@@ -18,8 +21,12 @@ import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.api.security.SanitizedFilename;
|
||||
import dev.caskeleton.application.fileserver.port.in.CopyFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferAdmissionController;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferPermit;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort;
|
||||
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;
|
||||
@@ -27,7 +34,13 @@ import java.time.Clock;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Copies a readable file into a new file the caller owns. */
|
||||
/**
|
||||
* Copies a readable file into a new file the caller owns.
|
||||
*
|
||||
* <p>A copy writes new bytes, so it passes the same capacity checks an upload does: {@link
|
||||
* TransferAdmissionController} refuses it at the hard high-water mark, and the target namespace's
|
||||
* quota is reserved before the bytes move and committed with the record's publication.
|
||||
*/
|
||||
@RequiresPermission("file:copy")
|
||||
@UseCaseCapability(
|
||||
transactionMode = TransactionMode.WRITE,
|
||||
@@ -40,8 +53,11 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase {
|
||||
|
||||
private final FileMetadataPort metadataStore;
|
||||
private final CopyContentPort copyGateway;
|
||||
private final FileQuotaPort quotaService;
|
||||
private final TransferAdmissionController admissionController;
|
||||
private final FileAccessPolicyPort accessPolicy;
|
||||
private final OriginalFilenamePolicy filenamePolicy;
|
||||
private final UploadPolicy uploadPolicy;
|
||||
private final UploadIdentifierPort identifierFactory;
|
||||
private final TransactionPort transactions;
|
||||
private final Clock clock;
|
||||
@@ -49,15 +65,19 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase {
|
||||
public CopyFileApplicationUseCase(
|
||||
FileMetadataPort metadataStore,
|
||||
CopyContentPort copyGateway,
|
||||
FileAccessPolicyPort accessPolicy,
|
||||
OriginalFilenamePolicy filenamePolicy,
|
||||
UploadPolicies policies,
|
||||
FileQuotaPort quotaService,
|
||||
TransferAdmissionController admissionController,
|
||||
UploadIdentifierPort identifierFactory,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore");
|
||||
this.copyGateway = Objects.requireNonNull(copyGateway, "copyGateway");
|
||||
this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy");
|
||||
this.filenamePolicy = Objects.requireNonNull(filenamePolicy, "filenamePolicy");
|
||||
this.quotaService = Objects.requireNonNull(quotaService, "quotaService");
|
||||
this.admissionController = Objects.requireNonNull(admissionController, "admissionController");
|
||||
this.accessPolicy = policies.access();
|
||||
this.filenamePolicy = policies.filenames();
|
||||
this.uploadPolicy = policies.upload();
|
||||
this.identifierFactory = Objects.requireNonNull(identifierFactory, "identifierFactory");
|
||||
this.transactions = Objects.requireNonNull(transactions, "transactions");
|
||||
this.clock = Objects.requireNonNull(clock, "clock");
|
||||
@@ -74,40 +94,68 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase {
|
||||
|
||||
SanitizedFilename filename =
|
||||
filenamePolicy.sanitize(command.targetFilename().orElse(source.originalName()));
|
||||
FileId targetId = identifierFactory.newFileId();
|
||||
FileRecord target =
|
||||
transactions.inWrite(
|
||||
() ->
|
||||
metadataStore.insert(
|
||||
new FileRecordDraft(
|
||||
targetId,
|
||||
command.targetNamespace(),
|
||||
filename.value(),
|
||||
source.verifiedMediaType().or(source::claimedMediaType),
|
||||
source.actualSize(),
|
||||
// The copy belongs to whoever made it, not to the source's owner.
|
||||
context.subject().asOwner())));
|
||||
long bytes = source.actualSize().orElseThrow(CopyFileApplicationUseCase::readyWithoutSize);
|
||||
QuotaScope scope = QuotaScope.ofNamespace(command.targetNamespace().value());
|
||||
|
||||
StoredContent copied;
|
||||
try {
|
||||
copied =
|
||||
copyGateway.copyCreateOnly(
|
||||
source.contentKey().orElseThrow(CopyFileApplicationUseCase::readyWithoutKey),
|
||||
command.targetNamespace());
|
||||
} catch (RuntimeException failure) {
|
||||
// The target may exist as a partial object; no rollback is promised, so it is queued for the
|
||||
// cleanup worker instead of being left for an orphan scan to find much later.
|
||||
failRecord(target, "COPY_FAILED");
|
||||
throw failure;
|
||||
// A copy adds as many bytes to the pool as an upload of the same file, so it is admitted the
|
||||
// same way: the hard high-water mark and the caller's concurrency, held for the whole transfer.
|
||||
try (TransferPermit permit =
|
||||
admissionController.acquireUpload(
|
||||
TransferAdmissionController.callerScope(context), bytes)) {
|
||||
FileId targetId = identifierFactory.newFileId();
|
||||
CopyTarget target =
|
||||
transactions.inWrite(
|
||||
() ->
|
||||
new CopyTarget(
|
||||
quotaService.reserve(scope, bytes, uploadPolicy.reservationTtl()),
|
||||
metadataStore.insert(
|
||||
new FileRecordDraft(
|
||||
targetId,
|
||||
command.targetNamespace(),
|
||||
filename.value(),
|
||||
source.verifiedMediaType().or(source::claimedMediaType),
|
||||
source.actualSize(),
|
||||
// The copy belongs to whoever made it, not to the source's owner.
|
||||
context.subject().asOwner()))));
|
||||
|
||||
StoredContent copied;
|
||||
try {
|
||||
copied =
|
||||
copyGateway.copyCreateOnly(
|
||||
source.contentKey().orElseThrow(CopyFileApplicationUseCase::readyWithoutKey),
|
||||
command.targetNamespace());
|
||||
} catch (RuntimeException failure) {
|
||||
// The target may exist as a partial object; no rollback is promised, so it is queued for
|
||||
// the cleanup worker instead of being left for an orphan scan to find much later.
|
||||
try {
|
||||
transactions.inWrite(
|
||||
() -> {
|
||||
failRecord(target.record(), "COPY_FAILED");
|
||||
quotaService.release(target.reservation());
|
||||
});
|
||||
} catch (RuntimeException compensationFailure) {
|
||||
failure.addSuppressed(compensationFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
return FileView.of(publish(target, copied).toDescriptor());
|
||||
}
|
||||
return FileView.of(publish(target, copied).toDescriptor());
|
||||
}
|
||||
|
||||
/** The reservation and the record one copy opens, so a single boundary can return both. */
|
||||
private record CopyTarget(QuotaReservation reservation, FileRecord record) {}
|
||||
|
||||
/** Walks the copied target to READY through the same edges an upload would take. */
|
||||
private FileRecord publish(FileRecord target, StoredContent copied) {
|
||||
// Four hops, one boundary. The intermediate states exist to satisfy the transition table, not
|
||||
// to be observable; a copy that stalled on one of them would look like a stuck upload.
|
||||
return transactions.inWrite(() -> publishSteps(target, copied));
|
||||
private FileRecord publish(CopyTarget target, StoredContent copied) {
|
||||
// Four hops and the quota commit, one boundary. The intermediate states exist to satisfy the
|
||||
// transition table, not to be observable; a copy that stalled on one of them would look like a
|
||||
// stuck upload.
|
||||
return transactions.inWrite(
|
||||
() -> {
|
||||
FileRecord ready = publishSteps(target.record(), copied);
|
||||
quotaService.commit(target.reservation(), copied.size());
|
||||
return ready;
|
||||
});
|
||||
}
|
||||
|
||||
private FileRecord publishSteps(FileRecord target, StoredContent copied) {
|
||||
@@ -148,25 +196,26 @@ public class CopyFileApplicationUseCase implements CopyFileUseCase {
|
||||
* one path it permits, through UPLOADING.
|
||||
*/
|
||||
private void failRecord(FileRecord record, String reasonCode) {
|
||||
transactions.inWrite(
|
||||
() -> {
|
||||
FileRecord uploading =
|
||||
metadataStore.transition(
|
||||
record.fileId(),
|
||||
record.version(),
|
||||
FileState.CREATED,
|
||||
FileState.UPLOADING,
|
||||
FileRecordMutation.none());
|
||||
metadataStore.transition(
|
||||
uploading.fileId(),
|
||||
uploading.version(),
|
||||
FileState.UPLOADING,
|
||||
FileState.FAILED,
|
||||
FileRecordMutation.failure(reasonCode));
|
||||
});
|
||||
FileRecord uploading =
|
||||
metadataStore.transition(
|
||||
record.fileId(),
|
||||
record.version(),
|
||||
FileState.CREATED,
|
||||
FileState.UPLOADING,
|
||||
FileRecordMutation.none());
|
||||
metadataStore.transition(
|
||||
uploading.fileId(),
|
||||
uploading.version(),
|
||||
FileState.UPLOADING,
|
||||
FileState.FAILED,
|
||||
FileRecordMutation.failure(reasonCode));
|
||||
}
|
||||
|
||||
private static IllegalStateException readyWithoutKey() {
|
||||
return new IllegalStateException("READY record has no content key");
|
||||
}
|
||||
|
||||
private static IllegalStateException readyWithoutSize() {
|
||||
return new IllegalStateException("READY record has no size");
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -4,6 +4,7 @@ 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.QuotaScope;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.OptionalDouble;
|
||||
@@ -43,6 +44,17 @@ public final class TransferAdmissionController {
|
||||
this.overflowScopeUploads = new Semaphore(properties.scopeUploadPermits());
|
||||
}
|
||||
|
||||
/**
|
||||
* The scope a caller's transfers are admitted under: the caller, not the namespace.
|
||||
*
|
||||
* <p>Counting it per namespace put every caller of a deployment — which uploads into one default
|
||||
* namespace — behind the same handful of permits, so one busy client refused everyone else. Every
|
||||
* write that adds bytes to the pool (upload create, append, copy) takes its permit here.
|
||||
*/
|
||||
public static QuotaScope callerScope(RequestContext context) {
|
||||
return QuotaScope.ofPrincipal(context.subject().principalId());
|
||||
}
|
||||
|
||||
public TransferPermit acquireUpload(QuotaScope scope, long requestedBytes) {
|
||||
requireWithinFileSizePolicy(requestedBytes);
|
||||
requireBelowHardHighWater();
|
||||
|
||||
+2
-1
@@ -96,7 +96,8 @@ public class AppendUploadApplicationUseCase implements AppendUploadUseCase {
|
||||
|
||||
try (TransferPermit permit =
|
||||
admissionController.acquireUpload(
|
||||
UploadSessions.admissionScope(context), Math.max(command.contentLength(), 0))) {
|
||||
TransferAdmissionController.callerScope(context),
|
||||
Math.max(command.contentLength(), 0))) {
|
||||
WriterLease lease = leaseCoordinator.acquire(uploadId, context.instanceId());
|
||||
// The fence is what carries the lease through the transfer. It renews on its own heartbeat
|
||||
// and refuses the next write the moment renewal is denied, so a transfer that outlives its
|
||||
|
||||
+1
-1
@@ -104,7 +104,7 @@ public class CreateUploadApplicationUseCase implements CreateUploadUseCase {
|
||||
|
||||
try (TransferPermit permit =
|
||||
admissionController.acquireUpload(
|
||||
UploadSessions.admissionScope(context), reservationBytes)) {
|
||||
TransferAdmissionController.callerScope(context), reservationBytes)) {
|
||||
FileId fileId = identifierFactory.newFileId();
|
||||
UploadId uploadId = identifierFactory.newUploadId();
|
||||
|
||||
|
||||
-12
@@ -5,10 +5,8 @@ import dev.caskeleton.application.fileserver.api.error.FileNotFoundException;
|
||||
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.QuotaScope;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSession;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import java.time.Instant;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
@@ -52,16 +50,6 @@ final class UploadSessions {
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer concurrency is counted per caller.
|
||||
*
|
||||
* <p>Counting it per namespace put every caller of a deployment — which uploads into one default
|
||||
* namespace — behind the same handful of permits, so one busy client refused everyone else.
|
||||
*/
|
||||
static QuotaScope admissionScope(RequestContext context) {
|
||||
return QuotaScope.ofPrincipal(context.subject().principalId());
|
||||
}
|
||||
|
||||
static long effectiveMaximum(UploadPolicy policy, OptionalLong expectedLength) {
|
||||
return expectedLength.isPresent()
|
||||
? Math.min(policy.maximumFileSize(), Math.max(expectedLength.getAsLong(), 1))
|
||||
|
||||
+25
@@ -2,13 +2,17 @@ package dev.caskeleton.application.fileserver.download;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.ByteRange;
|
||||
import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileNotFoundException;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileRecord;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessSubject;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileOperation;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.port.in.DescribeFileQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.PrepareDownloadQuery;
|
||||
@@ -20,7 +24,9 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DownloadUseCasesTest {
|
||||
@@ -66,6 +72,25 @@ class DownloadUseCasesTest {
|
||||
assertThat(content.neverOpened()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 사용자가 만든 파일은 다운로드를 준비할 수 없다")
|
||||
void preparingADownloadOfAFileAnotherCallerOwnsIsRefused() {
|
||||
// given
|
||||
FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
|
||||
RequestContext stranger =
|
||||
new RequestContext(FileAccessSubject.of("user-2", Set.of("uploader")), "trace-2", "node-a");
|
||||
|
||||
// when
|
||||
Throwable failure =
|
||||
catchThrowable(() -> prepare.handle(new PrepareDownloadQuery(ready.fileId(), stranger)));
|
||||
|
||||
// then
|
||||
assertThat(failure)
|
||||
.isInstanceOfSatisfying(
|
||||
FileserverException.class,
|
||||
refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.ACCESS_DENIED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonReadyFileIsRejectedAndNeverOpened() {
|
||||
FileRecord verifying = ReadyFileFixture.verifying(metadata, SIZE, DIGEST);
|
||||
|
||||
+118
-2
@@ -2,24 +2,33 @@ package dev.caskeleton.application.fileserver.lifecycle;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
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.StorageNamespace;
|
||||
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.FileRecord;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessSubject;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileOperation;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupRequest;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupType;
|
||||
import dev.caskeleton.application.fileserver.port.in.CopyFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.DeleteFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.MoveFileCommand;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferAdmissionController;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties;
|
||||
import dev.caskeleton.application.fileserver.testkit.DirectTransactions;
|
||||
import dev.caskeleton.application.fileserver.testkit.FakeCopyContentGateway;
|
||||
import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy;
|
||||
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;
|
||||
@@ -27,18 +36,25 @@ import dev.caskeleton.application.fileserver.testkit.InMemoryUploadSessionStore;
|
||||
import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture;
|
||||
import dev.caskeleton.application.fileserver.testkit.SequentialUploadIdentifierFactory;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadPolicies;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadPolicy;
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileLifecycleUseCasesTest {
|
||||
|
||||
private static final String DIGEST = "f".repeat(64);
|
||||
private static final long SIZE = 10;
|
||||
private static final long MAX_FILE = 1024;
|
||||
private static final StorageNamespace TARGET = StorageNamespace.of("tenant-b");
|
||||
|
||||
private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore();
|
||||
private final FakeCopyContentGateway copyGateway = new FakeCopyContentGateway();
|
||||
@@ -52,12 +68,22 @@ class FileLifecycleUseCasesTest {
|
||||
new DeleteFileApplicationUseCase(
|
||||
metadata, accessPolicy, cleanup, sessions, sessions, transactions);
|
||||
|
||||
private final FakeFileQuotaService quota = new FakeFileQuotaService();
|
||||
|
||||
/** How full the pool reads; the standard profile refuses writes from 0.85. */
|
||||
private OptionalDouble storageUsed = OptionalDouble.empty();
|
||||
|
||||
private final CopyFileApplicationUseCase copy =
|
||||
new CopyFileApplicationUseCase(
|
||||
metadata,
|
||||
copyGateway,
|
||||
accessPolicy,
|
||||
OriginalFilenamePolicy.standard(),
|
||||
new UploadPolicies(
|
||||
accessPolicy,
|
||||
OriginalFilenamePolicy.standard(),
|
||||
UploadPolicy.standard(FileserverFixtures.NAMESPACE)),
|
||||
quota,
|
||||
new TransferAdmissionController(
|
||||
TransferAdmissionProperties.standard(), () -> storageUsed, MAX_FILE),
|
||||
new SequentialUploadIdentifierFactory(),
|
||||
transactions,
|
||||
Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC));
|
||||
@@ -229,6 +255,96 @@ class FileLifecycleUseCasesTest {
|
||||
assertThat(copyGateway.copies()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("저장소가 hard high-water를 넘으면 복사는 레코드도 바이트도 만들지 않고 STORAGE_FULL로 거절된다")
|
||||
void copyAtTheHardHighWaterMarkIsRefusedBeforeAnyRecordOrByteIsWritten() {
|
||||
// given
|
||||
FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
|
||||
copyGateway.copiesContentOf(SIZE, DIGEST);
|
||||
storageUsed = OptionalDouble.of(0.90);
|
||||
|
||||
// when
|
||||
Throwable failure = catchThrowable(() -> copy.handle(copyOf(source)));
|
||||
|
||||
// then
|
||||
assertThat(failure)
|
||||
.isInstanceOfSatisfying(
|
||||
FileserverException.class,
|
||||
refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.STORAGE_FULL));
|
||||
assertThat(
|
||||
List.of(
|
||||
copyGateway.copies(),
|
||||
metadata.find(nextCopyId()).isPresent(),
|
||||
quota.reservationCount()))
|
||||
.containsExactly(List.of(), false, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("복사는 대상 namespace에 쿼터를 예약하고 복사된 크기로 확정한다")
|
||||
void copyReservesQuotaInTheTargetNamespaceAndCommitsTheCopiedSize() {
|
||||
// given
|
||||
FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
|
||||
copyGateway.copiesContentOf(SIZE, DIGEST);
|
||||
|
||||
// when
|
||||
copy.handle(copyOf(source));
|
||||
|
||||
// then
|
||||
assertThat(List.of(quota.reservedScopes(), quota.committedBytes(), quota.anyReleased()))
|
||||
.containsExactly(List.of(QuotaScope.ofNamespace(TARGET.value())), List.of(SIZE), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("복사가 실패하면 예약한 쿼터를 확정하지 않고 돌려준다")
|
||||
void aFailedCopyReleasesItsQuotaReservationInsteadOfCommittingIt() {
|
||||
// given
|
||||
FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
|
||||
copyGateway.failNextCopy();
|
||||
|
||||
// when
|
||||
Throwable failure = catchThrowable(() -> copy.handle(copyOf(source)));
|
||||
|
||||
// then
|
||||
assertThat(failure).isInstanceOf(FileserverException.class);
|
||||
assertThat(List.of(quota.reservationCount(), quota.anyReleased(), quota.committedBytes()))
|
||||
.containsExactly(1, true, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 사용자가 만든 파일은 file:copy 권한이 있어도 복사할 수 없다")
|
||||
void copyingAFileAnotherCallerOwnsIsRefusedAndCopiesNothing() {
|
||||
// given
|
||||
FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
|
||||
copyGateway.copiesContentOf(SIZE, DIGEST);
|
||||
RequestContext stranger =
|
||||
new RequestContext(FileAccessSubject.of("user-2", Set.of("uploader")), "trace-2", "node-a");
|
||||
|
||||
// when
|
||||
Throwable failure =
|
||||
catchThrowable(
|
||||
() ->
|
||||
copy.handle(
|
||||
new CopyFileCommand(
|
||||
source.fileId(), TARGET, Optional.empty(), Optional.empty(), stranger)));
|
||||
|
||||
// then
|
||||
assertThat(failure)
|
||||
.isInstanceOfSatisfying(
|
||||
FileserverException.class,
|
||||
refused -> assertThat(refused.code()).isEqualTo(FileserverErrorCode.ACCESS_DENIED));
|
||||
assertThat(copyGateway.copies()).isEmpty();
|
||||
}
|
||||
|
||||
private static CopyFileCommand copyOf(FileRecord source) {
|
||||
return new CopyFileCommand(
|
||||
source.fileId(), TARGET, Optional.empty(), Optional.empty(), FileserverFixtures.context());
|
||||
}
|
||||
|
||||
/** The id the copy would give its target: the identifier factory's first file id. */
|
||||
private static FileId nextCopyId() {
|
||||
return new SequentialUploadIdentifierFactory().newFileId();
|
||||
}
|
||||
|
||||
@Test
|
||||
void moveChangesOnlyTheNamespaceAndNeverTheContentKey() {
|
||||
FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST);
|
||||
|
||||
+13
-1
@@ -13,7 +13,13 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/** Hand-rolled access policy that can deny a named operation and records what it was asked. */
|
||||
/**
|
||||
* Hand-rolled access policy that can deny a named operation and records what it was asked.
|
||||
*
|
||||
* <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.
|
||||
*/
|
||||
public final class FakeFileAccessPolicy implements FileAccessPolicyPort {
|
||||
|
||||
private final Set<FileOperation> denied = EnumSet.noneOf(FileOperation.class);
|
||||
@@ -36,5 +42,11 @@ 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()))) {
|
||||
throw new FileserverException(
|
||||
"subject does not own the file",
|
||||
FileserverFailureContext.of(FileserverErrorCode.ACCESS_DENIED, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -48,6 +48,10 @@ public final class FakeFileQuotaService implements FileQuotaPort {
|
||||
released.add(reservation);
|
||||
}
|
||||
|
||||
public List<QuotaScope> reservedScopes() {
|
||||
return reserved.stream().map(QuotaReservation::scope).toList();
|
||||
}
|
||||
|
||||
public int reservationCount() {
|
||||
return reserved.size();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user