review-followup Wave 3 라운드 3(P28·P29): fileserver use case·file:* 권한, 보안 파일 primitive 공용화, jvm-test-suite
- 결정 32: fileserver transport 연산 21개를 `port.in` use case로, 쓰기·읽기에 `file:*` 권한(소유자·tenant 정책은 유지), inbound 서비스 이름 `*UseCase`, port 구현 이름 `<Tech><Port>` 규칙(S2-#13b, 24개) - 디렉터리 descriptor 파일 primitive를 `adapter:outbound:support`로(S4-lead-2 일부 — fileserver는 번역만), persistence-fileserver를 scan·클래스별 조건 대신 명시적 `@Bean` 설정으로(S2-#8a 일부), `FileVerifier`를 adapter로 - 호출자 0인 `poster.image-attached` 이벤트 삭제, SES SDK client를 레지스트리 종료 때 close, fileserver migration V1–V5 고정 - P29: auxiliary 레인 → Gradle `jvm-test-suite`(BUILD-O3-5, build-logic 16,768 → 5,851줄), redis-sdk가 runtime을 api로(P22-new-3) - 통합: JPA API surface 기준선 재승인(이름 규칙 변경), migration lane에 V19 반영, messaging 통합 테스트가 jar 안 migration 목록 조회(ORCH-new-5) - P28·P29 에이전트가 세션 재시작으로 중단 — 커밋된 것만 합치고 결과 파일은 오케스트레이터가 확정, S6-#10a는 P30으로 검증: ./gradlew ci verifyDependencyLocks --warning-mode=fail(714 task) · mainCheck architectureCheck verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys configContractCheck · :app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest integrationCheck · -p build-logic test · -p optional-platforms ci · releaseCheck qualificationBootJar 통과 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
09e2dd63d6
commit
0579935746
@@ -2,7 +2,6 @@ plugins {
|
||||
id 'ca.spring-library'
|
||||
id 'ca.spring-config'
|
||||
id 'java-test-fixtures'
|
||||
id 'ca.auxiliary-source-set'
|
||||
id 'ca.api-surface'
|
||||
}
|
||||
|
||||
@@ -18,8 +17,18 @@ plugins {
|
||||
// coordinates the BOM does not manage).
|
||||
description = 'Inbound adapter: GraphQL API (Spring for GraphQL, GraphQL execution platform)'
|
||||
|
||||
auxiliarySourceSets {
|
||||
sourceSet('systemTest') { compilesAgainst 'main' }
|
||||
testing {
|
||||
suites {
|
||||
systemTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
configurations {
|
||||
systemTestImplementation.extendsFrom testImplementation
|
||||
systemTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
}
|
||||
|
||||
|
||||
|
||||
+60
-20
@@ -3,16 +3,30 @@ package dev.caskeleton.adapter.inbound.web.fileserver.admin;
|
||||
import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory;
|
||||
import dev.caskeleton.application.fileserver.admin.FileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.ForceDeleteCommand;
|
||||
import dev.caskeleton.application.fileserver.admin.IncompleteUploadView;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanObject;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanReconcileCommand;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanReconcileReport;
|
||||
import dev.caskeleton.application.fileserver.admin.RuntimeCapabilityReport;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthReport;
|
||||
import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult;
|
||||
import dev.caskeleton.application.fileserver.port.in.CleanupUploadsCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.CleanupUploadsUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ForceDeleteCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.ForceDeleteFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetRuntimeCapabilitiesQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetRuntimeCapabilitiesUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetStorageHealthQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetStorageHealthUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ListIncompleteUploadsQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.ListIncompleteUploadsUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ListOrphansQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.ListOrphansUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.OrphanReconcileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.ReconcileOrphansUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ReverifyFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.ReverifyFileUseCase;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
@@ -39,18 +53,40 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = {"enabled", "admin.enabled"},
|
||||
name = "admin.enabled",
|
||||
havingValue = "true")
|
||||
public class FileserverAdminController {
|
||||
|
||||
private static final int DEFAULT_PAGE = 100;
|
||||
|
||||
private final FileserverAdminService adminService;
|
||||
private final GetStorageHealthUseCase storageHealth;
|
||||
private final GetRuntimeCapabilitiesUseCase capabilities;
|
||||
private final ListOrphansUseCase orphans;
|
||||
private final ReconcileOrphansUseCase reconcileOrphans;
|
||||
private final ReverifyFileUseCase reverify;
|
||||
private final ForceDeleteFileUseCase forceDelete;
|
||||
private final ListIncompleteUploadsUseCase incompleteUploads;
|
||||
private final CleanupUploadsUseCase cleanupUploads;
|
||||
private final FileserverRequestContextFactory contextFactory;
|
||||
|
||||
public FileserverAdminController(
|
||||
FileserverAdminService adminService, FileserverRequestContextFactory contextFactory) {
|
||||
this.adminService = adminService;
|
||||
GetStorageHealthUseCase storageHealth,
|
||||
GetRuntimeCapabilitiesUseCase capabilities,
|
||||
ListOrphansUseCase orphans,
|
||||
ReconcileOrphansUseCase reconcileOrphans,
|
||||
ReverifyFileUseCase reverify,
|
||||
ForceDeleteFileUseCase forceDelete,
|
||||
ListIncompleteUploadsUseCase incompleteUploads,
|
||||
CleanupUploadsUseCase cleanupUploads,
|
||||
FileserverRequestContextFactory contextFactory) {
|
||||
this.storageHealth = storageHealth;
|
||||
this.capabilities = capabilities;
|
||||
this.orphans = orphans;
|
||||
this.reconcileOrphans = reconcileOrphans;
|
||||
this.reverify = reverify;
|
||||
this.forceDelete = forceDelete;
|
||||
this.incompleteUploads = incompleteUploads;
|
||||
this.cleanupUploads = cleanupUploads;
|
||||
this.contextFactory = contextFactory;
|
||||
}
|
||||
|
||||
@@ -58,19 +94,19 @@ public class FileserverAdminController {
|
||||
path = "/internal/fileserver/storage-health",
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public StorageHealthReport storageHealth() {
|
||||
return adminService.storageHealth(contextFactory.current());
|
||||
return storageHealth.handle(new GetStorageHealthQuery(contextFactory.current()));
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
path = "/internal/fileserver/capabilities",
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public RuntimeCapabilityReport capabilities() {
|
||||
return adminService.capabilities(contextFactory.current());
|
||||
return capabilities.handle(new GetRuntimeCapabilitiesQuery(contextFactory.current()));
|
||||
}
|
||||
|
||||
@GetMapping(path = "/internal/fileserver/orphans", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public List<OrphanObject> orphans(@RequestParam(name = "limit", defaultValue = "100") int limit) {
|
||||
return adminService.orphans(limit, contextFactory.current());
|
||||
return orphans.handle(new ListOrphansQuery(limit, contextFactory.current()));
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
@@ -78,7 +114,7 @@ public class FileserverAdminController {
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public OrphanReconcileReport reconcileOrphans(@RequestBody OrphanReconcileHttpRequest request) {
|
||||
return adminService.reconcileOrphans(toCommand(request), contextFactory.current());
|
||||
return reconcileOrphans.handle(toCommand(request, contextFactory.current()));
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
@@ -86,7 +122,7 @@ public class FileserverAdminController {
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public UploadedFileResponse reverify(@PathVariable("fileId") String fileId) {
|
||||
return UploadedFileResponse.from(
|
||||
adminService.reverify(FileId.parse(fileId), contextFactory.current()));
|
||||
reverify.handle(new ReverifyFileCommand(FileId.parse(fileId), contextFactory.current())));
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
@@ -94,9 +130,9 @@ public class FileserverAdminController {
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<Void> forceDelete(
|
||||
@PathVariable("fileId") String fileId, @Valid @RequestBody ForceDeleteHttpRequest request) {
|
||||
adminService.forceDelete(
|
||||
new ForceDeleteCommand(FileId.parse(fileId), request.reasonCode()),
|
||||
contextFactory.current());
|
||||
forceDelete.handle(
|
||||
new ForceDeleteCommand(
|
||||
FileId.parse(fileId), request.reasonCode(), contextFactory.current()));
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@@ -105,7 +141,8 @@ public class FileserverAdminController {
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public List<IncompleteUploadView> incompleteUploads(
|
||||
@RequestParam(name = "limit", defaultValue = "100") int limit) {
|
||||
return adminService.incompleteUploads(limit, contextFactory.current());
|
||||
return incompleteUploads.handle(
|
||||
new ListIncompleteUploadsQuery(limit, contextFactory.current()));
|
||||
}
|
||||
|
||||
@PostMapping(
|
||||
@@ -114,7 +151,8 @@ public class FileserverAdminController {
|
||||
public CleanupBatchResult cleanupUploads(
|
||||
@RequestParam(name = "maxItems", defaultValue = "100") int maxItems,
|
||||
@RequestParam(name = "maxBytes", defaultValue = "1073741824") long maxBytes) {
|
||||
return adminService.cleanupUploads(maxItems, maxBytes, contextFactory.current());
|
||||
return cleanupUploads.handle(
|
||||
new CleanupUploadsCommand(maxItems, maxBytes, contextFactory.current()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,17 +161,19 @@ public class FileserverAdminController {
|
||||
* <p>Every absent field resolves to the safe value: a dry run, the default page, and no
|
||||
* fingerprints. Nothing here can be omitted into a destructive default.
|
||||
*/
|
||||
private static OrphanReconcileCommand toCommand(OrphanReconcileHttpRequest request) {
|
||||
private static OrphanReconcileCommand toCommand(
|
||||
OrphanReconcileHttpRequest request, RequestContext context) {
|
||||
boolean dryRun = request.dryRun() == null || request.dryRun();
|
||||
int limit = request.limit() == null ? DEFAULT_PAGE : request.limit();
|
||||
if (dryRun) {
|
||||
return OrphanReconcileCommand.dryRun(limit);
|
||||
return OrphanReconcileCommand.dryRun(limit, context);
|
||||
}
|
||||
return new OrphanReconcileCommand(
|
||||
false,
|
||||
limit,
|
||||
request.maxBytes() == null ? 1L << 30 : request.maxBytes(),
|
||||
request.expectedFingerprints() == null ? List.of() : request.expectedFingerprints(),
|
||||
request.reasonCode() == null ? "ORPHAN_APPLY" : request.reasonCode());
|
||||
request.reasonCode() == null ? "ORPHAN_APPLY" : request.reasonCode(),
|
||||
context);
|
||||
}
|
||||
}
|
||||
|
||||
+11
-1
@@ -10,6 +10,8 @@ import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Supplier;
|
||||
import org.springframework.core.task.TaskRejectedException;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* Admission control for blocking transfers.
|
||||
@@ -43,7 +45,15 @@ public final class BlockingTransferExecutor {
|
||||
public <T> T call(Supplier<T> work) {
|
||||
Future<T> future;
|
||||
try {
|
||||
future = executor.submit(work::get);
|
||||
// The worker runs as the caller. Method security checks a use case's @RequiresPermission
|
||||
// against the security context of the thread that calls it, and a pool thread has none of
|
||||
// its own: without this an authenticated upload's append and finalize were refused as
|
||||
// anonymous. The delegate restores the worker's previous context afterwards, so nothing of
|
||||
// this request stays on the pooled thread for the next one.
|
||||
future =
|
||||
executor.submit(
|
||||
new DelegatingSecurityContextCallable<>(
|
||||
work::get, SecurityContextHolder.getContext()));
|
||||
} catch (TaskRejectedException rejected) {
|
||||
throw new FileserverException(
|
||||
"transfer pool is saturated",
|
||||
|
||||
+27
-16
@@ -14,17 +14,22 @@ import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestC
|
||||
import dev.caskeleton.application.fileserver.api.ByteRange;
|
||||
import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadDescriptor;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadRequest;
|
||||
import dev.caskeleton.application.fileserver.download.ZeroCopyTransferResult;
|
||||
import dev.caskeleton.application.fileserver.port.in.DescribeFileQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.DescribeFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.PrepareDownloadQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentUseCase;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -42,14 +47,12 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
*/
|
||||
@OwnsAbsoluteWebRoute
|
||||
@RestController
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class FileDownloadController {
|
||||
|
||||
private final DownloadApplicationService downloadService;
|
||||
private final DescribeFileUseCase describeFile;
|
||||
private final PrepareDownloadUseCase prepareDownload;
|
||||
private final OpenDownloadContentUseCase openContent;
|
||||
private final TransferDownloadContentUseCase transferContent;
|
||||
private final MvcConditionalRequestFactory conditionalFactory;
|
||||
private final HttpDownloadPlanner downloadPlanner;
|
||||
private final MvcDownloadResponseWriter responseWriter;
|
||||
@@ -67,7 +70,10 @@ public class FileDownloadController {
|
||||
* without saying so. Every construction site names its zero-copy policy.
|
||||
*/
|
||||
public FileDownloadController(
|
||||
DownloadApplicationService downloadService,
|
||||
DescribeFileUseCase describeFile,
|
||||
PrepareDownloadUseCase prepareDownload,
|
||||
OpenDownloadContentUseCase openContent,
|
||||
TransferDownloadContentUseCase transferContent,
|
||||
MvcConditionalRequestFactory conditionalFactory,
|
||||
HttpDownloadPlanner downloadPlanner,
|
||||
MvcDownloadResponseWriter responseWriter,
|
||||
@@ -75,7 +81,10 @@ public class FileDownloadController {
|
||||
BlockingTransferExecutor transferExecutor,
|
||||
NginxDownloadStrategy delegationStrategy,
|
||||
ZeroCopyEligibility zeroCopy) {
|
||||
this.downloadService = downloadService;
|
||||
this.describeFile = describeFile;
|
||||
this.prepareDownload = prepareDownload;
|
||||
this.openContent = openContent;
|
||||
this.transferContent = transferContent;
|
||||
this.conditionalFactory = conditionalFactory;
|
||||
this.downloadPlanner = downloadPlanner;
|
||||
this.responseWriter = responseWriter;
|
||||
@@ -88,7 +97,7 @@ public class FileDownloadController {
|
||||
@GetMapping(path = "/v1/files/{fileId}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public UploadedFileResponse describe(@PathVariable("fileId") String fileId) {
|
||||
return UploadedFileResponse.from(
|
||||
downloadService.describeFile(FileId.parse(fileId), contextFactory.current()));
|
||||
describeFile.handle(new DescribeFileQuery(FileId.parse(fileId), contextFactory.current())));
|
||||
}
|
||||
|
||||
@RequestMapping(
|
||||
@@ -104,7 +113,7 @@ public class FileDownloadController {
|
||||
RequestContext context = contextFactory.current();
|
||||
|
||||
DownloadDescriptor descriptor =
|
||||
downloadService.describe(new DownloadRequest(FileId.parse(fileId)), context);
|
||||
prepareDownload.handle(new PrepareDownloadQuery(FileId.parse(fileId), context));
|
||||
HttpDownloadDecision decision = downloadPlanner.plan(descriptor, conditional, inline);
|
||||
responseWriter.writeHeaders(decision, response);
|
||||
if (!decision.bodyExpected()) {
|
||||
@@ -150,8 +159,9 @@ public class FileDownloadController {
|
||||
try {
|
||||
if (zeroCopy.isEligible(true, range.length(), secure)) {
|
||||
ZeroCopyTransferResult transfer =
|
||||
downloadService.transferContent(
|
||||
descriptor, range, Channels.newChannel(response.getOutputStream()));
|
||||
transferContent.handle(
|
||||
new TransferDownloadContentQuery(
|
||||
descriptor, range, Channels.newChannel(response.getOutputStream())));
|
||||
if (transfer.isComplete()) {
|
||||
return null;
|
||||
}
|
||||
@@ -163,7 +173,8 @@ public class FileDownloadController {
|
||||
+ " bytes; the response is already committed and must not be re-sent"));
|
||||
}
|
||||
}
|
||||
try (ReadableByteChannel content = downloadService.openContent(descriptor, range)) {
|
||||
try (ReadableByteChannel content =
|
||||
openContent.handle(new OpenDownloadContentQuery(descriptor, range))) {
|
||||
responseWriter.writeBody(content, response);
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
|
||||
+12
-16
@@ -16,10 +16,11 @@ import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
|
||||
import dev.caskeleton.application.fileserver.port.in.UploadFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.SingleShotUploadService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -28,7 +29,6 @@ import java.nio.channels.Channels;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -47,14 +47,9 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
*/
|
||||
@OwnsAbsoluteWebRoute
|
||||
@RestController
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class FileUploadController {
|
||||
|
||||
private final SingleShotUploadService uploadService;
|
||||
private final UploadFileUseCase uploadFile;
|
||||
private final RawUploadRequestMapper rawMapper;
|
||||
private final MultipartUploadRequestMapper multipartMapper;
|
||||
private final FileserverRequestContextFactory contextFactory;
|
||||
@@ -62,13 +57,13 @@ public class FileUploadController {
|
||||
private final FileserverWebProperties properties;
|
||||
|
||||
public FileUploadController(
|
||||
SingleShotUploadService uploadService,
|
||||
UploadFileUseCase uploadFile,
|
||||
RawUploadRequestMapper rawMapper,
|
||||
MultipartUploadRequestMapper multipartMapper,
|
||||
FileserverRequestContextFactory contextFactory,
|
||||
BlockingTransferExecutor transferExecutor,
|
||||
FileserverWebProperties properties) {
|
||||
this.uploadService = uploadService;
|
||||
this.uploadFile = uploadFile;
|
||||
this.rawMapper = rawMapper;
|
||||
this.multipartMapper = multipartMapper;
|
||||
this.contextFactory = contextFactory;
|
||||
@@ -182,12 +177,13 @@ public class FileUploadController {
|
||||
intent.declaredLength(),
|
||||
intent.expectedSha256(),
|
||||
mode);
|
||||
return uploadService.upload(
|
||||
request,
|
||||
content,
|
||||
contentLength,
|
||||
new FinalizeUploadRequest(intent.expectedSha256(), false),
|
||||
context);
|
||||
return uploadFile.handle(
|
||||
new UploadFileCommand(
|
||||
request,
|
||||
content,
|
||||
contentLength,
|
||||
new FinalizeUploadRequest(intent.expectedSha256(), false),
|
||||
context));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+49
-25
@@ -9,11 +9,15 @@ import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
|
||||
import dev.caskeleton.application.fileserver.port.in.AppendUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.AppendUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.CreateUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.CreateUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.FinalizeUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.AppendUploadResult;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadSessionView;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
@@ -47,26 +51,29 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@ExperimentalApi(specification = "draft-ietf-httpbis-resumable-upload-12")
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = {"enabled", "httpbis-draft12.enabled"},
|
||||
name = "httpbis-draft12.enabled",
|
||||
havingValue = "true")
|
||||
public class Draft12UploadController {
|
||||
|
||||
private static final String DRAFT_PATH = "/v1/experimental/draft12/uploads";
|
||||
|
||||
private final UploadApplicationService uploadService;
|
||||
private final FinalizeUploadService finalizeService;
|
||||
private final CreateUploadUseCase create;
|
||||
private final AppendUploadUseCase append;
|
||||
private final FinalizeUploadUseCase finalizer;
|
||||
private final FileserverRequestContextFactory contextFactory;
|
||||
private final BlockingTransferExecutor transferExecutor;
|
||||
private final Draft12Properties draftProperties;
|
||||
|
||||
public Draft12UploadController(
|
||||
UploadApplicationService uploadService,
|
||||
FinalizeUploadService finalizeService,
|
||||
CreateUploadUseCase create,
|
||||
AppendUploadUseCase append,
|
||||
FinalizeUploadUseCase finalizer,
|
||||
FileserverRequestContextFactory contextFactory,
|
||||
BlockingTransferExecutor transferExecutor,
|
||||
Draft12Properties draftProperties) {
|
||||
this.uploadService = uploadService;
|
||||
this.finalizeService = finalizeService;
|
||||
this.create = create;
|
||||
this.append = append;
|
||||
this.finalizer = finalizer;
|
||||
this.contextFactory = contextFactory;
|
||||
this.transferExecutor = transferExecutor;
|
||||
this.draftProperties = draftProperties;
|
||||
@@ -86,14 +93,15 @@ public class Draft12UploadController {
|
||||
public ResponseEntity<Void> create(HttpServletRequest request) throws IOException {
|
||||
RequestContext context = contextFactory.current();
|
||||
UploadSessionView created =
|
||||
uploadService.create(
|
||||
new CreateUploadRequest(
|
||||
filename(request),
|
||||
Optional.empty(),
|
||||
declaredLength(request),
|
||||
Optional.empty(),
|
||||
UploadMode.EXPERIMENTAL_RESUMABLE),
|
||||
context);
|
||||
create.handle(
|
||||
new CreateUploadCommand(
|
||||
new CreateUploadRequest(
|
||||
filename(request),
|
||||
Optional.empty(),
|
||||
declaredLength(request),
|
||||
Optional.empty(),
|
||||
UploadMode.EXPERIMENTAL_RESUMABLE),
|
||||
context));
|
||||
|
||||
long offset = 0;
|
||||
long bodyLength = request.getContentLengthLong();
|
||||
@@ -103,15 +111,24 @@ public class Draft12UploadController {
|
||||
transferExecutor
|
||||
.call(
|
||||
() ->
|
||||
uploadService.append(
|
||||
created.uploadId(), 0, Channels.newChannel(body), bodyLength, context))
|
||||
append.handle(
|
||||
new AppendUploadCommand(
|
||||
created.uploadId(),
|
||||
0,
|
||||
Channels.newChannel(body),
|
||||
bodyLength,
|
||||
Optional.empty(),
|
||||
context)))
|
||||
.committedOffset();
|
||||
}
|
||||
if (isComplete(request)) {
|
||||
transferExecutor.call(
|
||||
() ->
|
||||
finalizeService.finalizeUpload(
|
||||
created.uploadId(), FinalizeUploadRequest.synchronousWithoutDigest(), context));
|
||||
finalizer.handle(
|
||||
new FinalizeUploadCommand(
|
||||
created.uploadId(),
|
||||
FinalizeUploadRequest.synchronousWithoutDigest(),
|
||||
context)));
|
||||
}
|
||||
return ResponseEntity.created(URI.create(DRAFT_PATH + "/" + created.uploadId().canonicalText()))
|
||||
.header(Draft12Headers.UPLOAD_OFFSET, String.valueOf(offset))
|
||||
@@ -136,13 +153,20 @@ public class Draft12UploadController {
|
||||
AppendUploadResult appended =
|
||||
transferExecutor.call(
|
||||
() ->
|
||||
uploadService.append(
|
||||
id, expectedOffset, Channels.newChannel(body), declared, context));
|
||||
append.handle(
|
||||
new AppendUploadCommand(
|
||||
id,
|
||||
expectedOffset,
|
||||
Channels.newChannel(body),
|
||||
declared,
|
||||
Optional.empty(),
|
||||
context)));
|
||||
if (complete) {
|
||||
transferExecutor.call(
|
||||
() ->
|
||||
finalizeService.finalizeUpload(
|
||||
id, FinalizeUploadRequest.synchronousWithoutDigest(), context));
|
||||
finalizer.handle(
|
||||
new FinalizeUploadCommand(
|
||||
id, FinalizeUploadRequest.synchronousWithoutDigest(), context)));
|
||||
}
|
||||
return ResponseEntity.noContent()
|
||||
.header(Draft12Headers.UPLOAD_OFFSET, String.valueOf(appended.committedOffset()))
|
||||
|
||||
+28
-21
@@ -6,14 +6,17 @@ import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory;
|
||||
import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.StorageNamespace;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.CopyFileCommand;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.DeleteOutcome;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.FileLifecycleService;
|
||||
import dev.caskeleton.application.fileserver.port.in.CopyFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.DeleteFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.DeleteFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.MoveFileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import jakarta.validation.Valid;
|
||||
import java.net.URI;
|
||||
import java.util.Optional;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -39,19 +42,21 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
*/
|
||||
@OwnsAbsoluteWebRoute
|
||||
@RestController
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class FileLifecycleController {
|
||||
|
||||
private final FileLifecycleService lifecycleService;
|
||||
private final DeleteFileUseCase delete;
|
||||
private final CopyFileUseCase copy;
|
||||
private final MoveFileUseCase move;
|
||||
private final FileserverRequestContextFactory contextFactory;
|
||||
|
||||
public FileLifecycleController(
|
||||
FileLifecycleService lifecycleService, FileserverRequestContextFactory contextFactory) {
|
||||
this.lifecycleService = lifecycleService;
|
||||
DeleteFileUseCase delete,
|
||||
CopyFileUseCase copy,
|
||||
MoveFileUseCase move,
|
||||
FileserverRequestContextFactory contextFactory) {
|
||||
this.delete = delete;
|
||||
this.copy = copy;
|
||||
this.move = move;
|
||||
this.contextFactory = contextFactory;
|
||||
}
|
||||
|
||||
@@ -60,8 +65,9 @@ public class FileLifecycleController {
|
||||
@PathVariable("fileId") String fileId,
|
||||
@RequestHeader(name = HttpHeaders.IF_MATCH, required = false) String ifMatch) {
|
||||
DeleteOutcome outcome =
|
||||
lifecycleService.delete(
|
||||
FileId.parse(fileId), expectedSha256(ifMatch), contextFactory.current());
|
||||
delete.handle(
|
||||
new DeleteFileCommand(
|
||||
FileId.parse(fileId), expectedSha256(ifMatch), contextFactory.current()));
|
||||
return outcome.physicalCleanupScheduled()
|
||||
? ResponseEntity.accepted().build()
|
||||
: ResponseEntity.noContent().build();
|
||||
@@ -76,13 +82,13 @@ public class FileLifecycleController {
|
||||
@RequestHeader(name = HttpHeaders.IF_MATCH, required = false) String ifMatch,
|
||||
@Valid @RequestBody RelocateFileRequest request) {
|
||||
FileView copied =
|
||||
lifecycleService.copy(
|
||||
copy.handle(
|
||||
new CopyFileCommand(
|
||||
FileId.parse(fileId),
|
||||
StorageNamespace.of(request.namespace()),
|
||||
Optional.ofNullable(request.filename()),
|
||||
expectedSha256(ifMatch)),
|
||||
contextFactory.current());
|
||||
expectedSha256(ifMatch),
|
||||
contextFactory.current()));
|
||||
return ResponseEntity.accepted()
|
||||
.location(URI.create("/v1/files/" + copied.fileId().canonicalText()))
|
||||
.body(UploadedFileResponse.from(copied));
|
||||
@@ -97,11 +103,12 @@ public class FileLifecycleController {
|
||||
@RequestHeader(name = HttpHeaders.IF_MATCH, required = false) String ifMatch,
|
||||
@Valid @RequestBody RelocateFileRequest request) {
|
||||
return UploadedFileResponse.from(
|
||||
lifecycleService.move(
|
||||
FileId.parse(fileId),
|
||||
StorageNamespace.of(request.namespace()),
|
||||
expectedSha256(ifMatch),
|
||||
contextFactory.current()));
|
||||
move.handle(
|
||||
new MoveFileCommand(
|
||||
FileId.parse(fileId),
|
||||
StorageNamespace.of(request.namespace()),
|
||||
expectedSha256(ifMatch),
|
||||
contextFactory.current())));
|
||||
}
|
||||
|
||||
private static Optional<String> expectedSha256(String ifMatch) {
|
||||
|
||||
-6
@@ -6,7 +6,6 @@ import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
|
||||
import dev.caskeleton.shared.response.Envelope;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -35,11 +34,6 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
* explicit exception (owner decision 12).
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class FileserverExceptionHandler {
|
||||
|
||||
|
||||
+49
-29
@@ -6,11 +6,19 @@ import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestC
|
||||
import dev.caskeleton.application.fileserver.api.UploadId;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.api.transfer.UploadMode;
|
||||
import dev.caskeleton.application.fileserver.port.in.AppendUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.AppendUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.CancelUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.CancelUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.CreateUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.CreateUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.FinalizeUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetUploadStatusQuery;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetUploadStatusUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.AppendUploadResult;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadSessionView;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
@@ -47,29 +55,38 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = {"enabled", "tus.enabled"},
|
||||
name = "tus.enabled",
|
||||
havingValue = "true")
|
||||
public class TusController {
|
||||
|
||||
private static final DateTimeFormatter HTTP_DATE =
|
||||
DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC);
|
||||
|
||||
private final UploadApplicationService uploadService;
|
||||
private final FinalizeUploadService finalizeService;
|
||||
private final CreateUploadUseCase create;
|
||||
private final GetUploadStatusUseCase status;
|
||||
private final AppendUploadUseCase append;
|
||||
private final FinalizeUploadUseCase finalizer;
|
||||
private final CancelUploadUseCase cancel;
|
||||
private final TusRequestParser parser;
|
||||
private final FileserverRequestContextFactory contextFactory;
|
||||
private final BlockingTransferExecutor transferExecutor;
|
||||
private final TusProperties tusProperties;
|
||||
|
||||
public TusController(
|
||||
UploadApplicationService uploadService,
|
||||
FinalizeUploadService finalizeService,
|
||||
CreateUploadUseCase create,
|
||||
GetUploadStatusUseCase status,
|
||||
AppendUploadUseCase append,
|
||||
FinalizeUploadUseCase finalizer,
|
||||
CancelUploadUseCase cancel,
|
||||
TusRequestParser parser,
|
||||
FileserverRequestContextFactory contextFactory,
|
||||
BlockingTransferExecutor transferExecutor,
|
||||
TusProperties tusProperties) {
|
||||
this.uploadService = uploadService;
|
||||
this.finalizeService = finalizeService;
|
||||
this.create = create;
|
||||
this.status = status;
|
||||
this.append = append;
|
||||
this.finalizer = finalizer;
|
||||
this.cancel = cancel;
|
||||
this.parser = parser;
|
||||
this.contextFactory = contextFactory;
|
||||
this.transferExecutor = transferExecutor;
|
||||
@@ -92,14 +109,15 @@ public class TusController {
|
||||
parser.requireProtocolVersion(request);
|
||||
RequestContext context = contextFactory.current();
|
||||
UploadSessionView created =
|
||||
uploadService.create(
|
||||
new CreateUploadRequest(
|
||||
parser.filename(request).orElse("upload.bin"),
|
||||
Optional.ofNullable(parser.metadata(request).get("filetype")),
|
||||
parser.declaredLength(request),
|
||||
Optional.empty(),
|
||||
UploadMode.RESUMABLE),
|
||||
context);
|
||||
create.handle(
|
||||
new CreateUploadCommand(
|
||||
new CreateUploadRequest(
|
||||
parser.filename(request).orElse("upload.bin"),
|
||||
Optional.ofNullable(parser.metadata(request).get("filetype")),
|
||||
parser.declaredLength(request),
|
||||
Optional.empty(),
|
||||
UploadMode.RESUMABLE),
|
||||
context));
|
||||
|
||||
return ResponseEntity.created(URI.create("/v1/uploads/" + created.uploadId().canonicalText()))
|
||||
.header(TusHeaders.RESUMABLE, tusProperties.version())
|
||||
@@ -113,7 +131,7 @@ public class TusController {
|
||||
@PathVariable("uploadId") String uploadId, HttpServletRequest request) {
|
||||
parser.requireProtocolVersion(request);
|
||||
UploadSessionView session =
|
||||
uploadService.status(UploadId.parse(uploadId), contextFactory.current());
|
||||
status.handle(new GetUploadStatusQuery(UploadId.parse(uploadId), contextFactory.current()));
|
||||
|
||||
ResponseEntity.HeadersBuilder<?> response =
|
||||
ResponseEntity.noContent()
|
||||
@@ -153,22 +171,24 @@ public class TusController {
|
||||
AppendUploadResult appended =
|
||||
transferExecutor.call(
|
||||
() ->
|
||||
uploadService.append(
|
||||
id,
|
||||
expectedOffset,
|
||||
Channels.newChannel(body),
|
||||
declared,
|
||||
expectedChunkSha256,
|
||||
context));
|
||||
append.handle(
|
||||
new AppendUploadCommand(
|
||||
id,
|
||||
expectedOffset,
|
||||
Channels.newChannel(body),
|
||||
declared,
|
||||
expectedChunkSha256,
|
||||
context)));
|
||||
|
||||
UploadSessionView session = uploadService.status(id, context);
|
||||
UploadSessionView session = status.handle(new GetUploadStatusQuery(id, context));
|
||||
if (isComplete(session, appended)) {
|
||||
// Finalize reads the whole object back and moves it: transfer work, bounded by the same
|
||||
// executor as the append rather than holding a servlet thread for it.
|
||||
transferExecutor.call(
|
||||
() ->
|
||||
finalizeService.finalizeUpload(
|
||||
id, FinalizeUploadRequest.synchronousWithoutDigest(), context));
|
||||
finalizer.handle(
|
||||
new FinalizeUploadCommand(
|
||||
id, FinalizeUploadRequest.synchronousWithoutDigest(), context)));
|
||||
}
|
||||
return ResponseEntity.noContent()
|
||||
.header(TusHeaders.RESUMABLE, tusProperties.version())
|
||||
@@ -181,7 +201,7 @@ public class TusController {
|
||||
public ResponseEntity<Void> terminate(
|
||||
@PathVariable("uploadId") String uploadId, HttpServletRequest request) {
|
||||
parser.requireProtocolVersion(request);
|
||||
uploadService.cancel(UploadId.parse(uploadId), contextFactory.current());
|
||||
cancel.handle(new CancelUploadCommand(UploadId.parse(uploadId), contextFactory.current()));
|
||||
return ResponseEntity.noContent().header(TusHeaders.RESUMABLE, tusProperties.version()).build();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ class FileserverAdminControllerTest {
|
||||
void setUp() {
|
||||
mvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new FileserverAdminController(adminService, FileserverWebFixtures.contextFactory()))
|
||||
adminService.controller(FileserverWebFixtures.contextFactory()))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package dev.caskeleton.adapter.inbound.web.fileserver.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
/**
|
||||
* A transfer runs as the caller that asked for it.
|
||||
*
|
||||
* <p>The upload use cases carry {@code @RequiresPermission}, which method security checks against
|
||||
* the security context of the thread that calls them. Append and finalize are called on the
|
||||
* transfer pool, so a worker that did not carry the request's context would be refused as an
|
||||
* anonymous caller, whoever had actually authenticated.
|
||||
*/
|
||||
class BlockingTransferExecutorSecurityContextTest {
|
||||
|
||||
private ThreadPoolTaskExecutor pool;
|
||||
|
||||
@BeforeEach
|
||||
void startPool() {
|
||||
pool = new ThreadPoolTaskExecutor();
|
||||
pool.setCorePoolSize(1);
|
||||
pool.setMaxPoolSize(1);
|
||||
pool.setQueueCapacity(1);
|
||||
pool.initialize();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopPool() {
|
||||
pool.shutdown();
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("전송 풀의 작업은 요청 스레드의 인증 정보로 실행된다")
|
||||
void workOnTheTransferPoolSeesTheCallersAuthentication() {
|
||||
// given
|
||||
Authentication caller =
|
||||
UsernamePasswordAuthenticationToken.authenticated(
|
||||
"uploader", "n/a", List.of(new SimpleGrantedAuthority("ROLE_FILE_WRITE")));
|
||||
SecurityContextHolder.getContext().setAuthentication(caller);
|
||||
BlockingTransferExecutor executor = new BlockingTransferExecutor(pool, 5);
|
||||
|
||||
// when
|
||||
Authentication seen =
|
||||
executor.call(() -> SecurityContextHolder.getContext().getAuthentication());
|
||||
|
||||
// then
|
||||
assertThat(seen).isSameAs(caller);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("작업이 끝난 전송 스레드에는 요청의 인증 정보가 남지 않는다")
|
||||
void theWorkerDoesNotKeepTheCallersAuthenticationAfterward() {
|
||||
// given
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(
|
||||
UsernamePasswordAuthenticationToken.authenticated("uploader", "n/a", List.of()));
|
||||
BlockingTransferExecutor executor = new BlockingTransferExecutor(pool, 5);
|
||||
executor.call(() -> null);
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
// when
|
||||
Authentication leftOver =
|
||||
executor.call(() -> SecurityContextHolder.getContext().getAuthentication());
|
||||
|
||||
// then
|
||||
assertThat(leftOver).isNull();
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -31,7 +31,10 @@ class FileDownloadControllerContractTest {
|
||||
mvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new FileDownloadController(
|
||||
downloadService,
|
||||
downloadService.describePort(),
|
||||
downloadService.preparePort(),
|
||||
downloadService.openPort(),
|
||||
downloadService.transferPort(),
|
||||
new MvcConditionalRequestFactory(),
|
||||
downloadService.httpPlanner(),
|
||||
new MvcDownloadResponseWriter(),
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ class FileUploadControllerTest {
|
||||
mvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new FileUploadController(
|
||||
uploadService,
|
||||
uploadService.port(),
|
||||
new RawUploadRequestMapper(false),
|
||||
new MultipartUploadRequestMapper(),
|
||||
FileserverWebFixtures.contextFactory(),
|
||||
|
||||
+3
-2
@@ -32,8 +32,9 @@ class Draft12ProtocolTest {
|
||||
mvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new Draft12UploadController(
|
||||
uploads,
|
||||
finalizeService,
|
||||
uploads.createPort(),
|
||||
uploads.appendPort(),
|
||||
finalizeService.port(),
|
||||
FileserverWebFixtures.contextFactory(),
|
||||
FileserverWebFixtures.transferExecutor(),
|
||||
DRAFT))
|
||||
|
||||
+4
-1
@@ -98,7 +98,10 @@ class NginxDownloadDelegationTest {
|
||||
private MockMvc mvc(NginxDelegationProperties properties) {
|
||||
return MockMvcBuilders.standaloneSetup(
|
||||
new FileDownloadController(
|
||||
downloadService,
|
||||
downloadService.describePort(),
|
||||
downloadService.preparePort(),
|
||||
downloadService.openPort(),
|
||||
downloadService.transferPort(),
|
||||
new MvcConditionalRequestFactory(),
|
||||
downloadService.httpPlanner(),
|
||||
new MvcDownloadResponseWriter(),
|
||||
|
||||
+5
-2
@@ -34,7 +34,7 @@ class FileserverHardeningContractTest {
|
||||
private final MockMvc uploadMvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new FileUploadController(
|
||||
uploads,
|
||||
uploads.port(),
|
||||
new RawUploadRequestMapper(false),
|
||||
new MultipartUploadRequestMapper(),
|
||||
FileserverWebFixtures.contextFactory(),
|
||||
@@ -46,7 +46,10 @@ class FileserverHardeningContractTest {
|
||||
private final MockMvc downloadMvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new FileDownloadController(
|
||||
downloads,
|
||||
downloads.describePort(),
|
||||
downloads.preparePort(),
|
||||
downloads.openPort(),
|
||||
downloads.transferPort(),
|
||||
new MvcConditionalRequestFactory(),
|
||||
downloads.httpPlanner(),
|
||||
new MvcDownloadResponseWriter(),
|
||||
|
||||
+35
-6
@@ -8,9 +8,12 @@ import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext;
|
||||
import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.port.in.AppendUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.CancelUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.CreateUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetUploadStatusUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.AppendUploadResult;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadSessionView;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
@@ -35,7 +38,7 @@ import java.util.UUID;
|
||||
* production service does. A chunk checksum is likewise compared with the digest of that chunk
|
||||
* alone, and a mismatch is rejected before the bytes are kept.
|
||||
*/
|
||||
public final class InMemoryUploadApplicationService implements UploadApplicationService {
|
||||
public final class InMemoryUploadApplicationService {
|
||||
|
||||
private final Map<UploadId, Session> sessions = new LinkedHashMap<>();
|
||||
private boolean expired;
|
||||
@@ -56,7 +59,6 @@ public final class InMemoryUploadApplicationService implements UploadApplication
|
||||
return require(uploadId).cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UploadSessionView create(CreateUploadRequest request, RequestContext context) {
|
||||
UploadId uploadId = UploadId.of(UUID.randomUUID());
|
||||
Session session = new Session(FileId.of(UUID.randomUUID()), request);
|
||||
@@ -64,7 +66,6 @@ public final class InMemoryUploadApplicationService implements UploadApplication
|
||||
return view(uploadId, session);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AppendUploadResult append(
|
||||
UploadId uploadId,
|
||||
long expectedOffset,
|
||||
@@ -91,12 +92,10 @@ public final class InMemoryUploadApplicationService implements UploadApplication
|
||||
session.buffer.size(), appended, sha256Hex(session.buffer.toByteArray()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public UploadSessionView status(UploadId uploadId, RequestContext context) {
|
||||
return view(uploadId, require(uploadId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel(UploadId uploadId, RequestContext context) {
|
||||
require(uploadId).cancelled = true;
|
||||
}
|
||||
@@ -170,4 +169,34 @@ public final class InMemoryUploadApplicationService implements UploadApplication
|
||||
this.request = request;
|
||||
}
|
||||
}
|
||||
|
||||
/** This fake as the create port. */
|
||||
public CreateUploadUseCase createPort() {
|
||||
return command -> create(command.request(), command.context());
|
||||
}
|
||||
|
||||
/** This fake as the append port. */
|
||||
public AppendUploadUseCase appendPort() {
|
||||
return command ->
|
||||
append(
|
||||
command.uploadId(),
|
||||
command.expectedOffset(),
|
||||
command.content(),
|
||||
command.contentLength(),
|
||||
command.expectedChunkSha256(),
|
||||
command.context());
|
||||
}
|
||||
|
||||
/** This fake as the status port. */
|
||||
public GetUploadStatusUseCase statusPort() {
|
||||
return query -> status(query.uploadId(), query.context());
|
||||
}
|
||||
|
||||
/** This fake as the cancel port. */
|
||||
public CancelUploadUseCase cancelPort() {
|
||||
return command -> {
|
||||
cancel(command.uploadId(), command.context());
|
||||
return null;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+48
-15
@@ -1,10 +1,9 @@
|
||||
package dev.caskeleton.adapter.inbound.web.fileserver.testkit;
|
||||
|
||||
import dev.caskeleton.application.fileserver.admin.FileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.ForceDeleteCommand;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.admin.FileserverAdminController;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory;
|
||||
import dev.caskeleton.application.fileserver.admin.IncompleteUploadView;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanObject;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanReconcileCommand;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanReconcileReport;
|
||||
import dev.caskeleton.application.fileserver.admin.RuntimeCapabilityReport;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthReport;
|
||||
@@ -17,6 +16,16 @@ import dev.caskeleton.application.fileserver.api.content.PublishMode;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult;
|
||||
import dev.caskeleton.application.fileserver.port.in.CleanupUploadsUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ForceDeleteCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.ForceDeleteFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetRuntimeCapabilitiesUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.GetStorageHealthUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ListIncompleteUploadsUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ListOrphansUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.OrphanReconcileCommand;
|
||||
import dev.caskeleton.application.fileserver.port.in.ReconcileOrphansUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.ReverifyFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -24,7 +33,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Admin service that records what the controller forwarded, without touching storage. */
|
||||
public final class RecordingAdminService implements FileserverAdminService {
|
||||
public final class RecordingAdminService {
|
||||
|
||||
private final List<ForceDeleteCommand> forceDeletes = new ArrayList<>();
|
||||
private OrphanReconcileCommand lastReconcile;
|
||||
@@ -42,12 +51,10 @@ public final class RecordingAdminService implements FileserverAdminService {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StorageHealthReport storageHealth(RequestContext context) {
|
||||
return new StorageHealthReport(1000, 400, 0.6, true, true, "linux-ext4", List.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
public RuntimeCapabilityReport capabilities(RequestContext context) {
|
||||
return new RuntimeCapabilityReport(
|
||||
"LOCAL",
|
||||
@@ -56,19 +63,15 @@ public final class RecordingAdminService implements FileserverAdminService {
|
||||
"linux-ext4");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<OrphanObject> orphans(int limit, RequestContext context) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public OrphanReconcileReport reconcileOrphans(
|
||||
OrphanReconcileCommand command, RequestContext context) {
|
||||
public OrphanReconcileReport reconcileOrphans(OrphanReconcileCommand command) {
|
||||
this.lastReconcile = command;
|
||||
return new OrphanReconcileReport(command.dryRun(), List.of(), 0, 0, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileView reverify(FileId fileId, RequestContext context) {
|
||||
return FileView.of(
|
||||
new FileDescriptor(
|
||||
@@ -84,12 +87,10 @@ public final class RecordingAdminService implements FileserverAdminService {
|
||||
1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forceDelete(ForceDeleteCommand command, RequestContext context) {
|
||||
public void forceDelete(ForceDeleteCommand command) {
|
||||
forceDeletes.add(command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<IncompleteUploadView> incompleteUploads(int limit, RequestContext context) {
|
||||
return List.of(
|
||||
new IncompleteUploadView(
|
||||
@@ -101,8 +102,40 @@ public final class RecordingAdminService implements FileserverAdminService {
|
||||
Optional.of(FileserverWebFixtures.NOW)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CleanupBatchResult cleanupUploads(int maxItems, long maxBytes, RequestContext context) {
|
||||
return CleanupBatchResult.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin controller over this fake, one port per operation.
|
||||
*
|
||||
* @param contextFactory the request context source
|
||||
* @return the controller
|
||||
*/
|
||||
public FileserverAdminController controller(FileserverRequestContextFactory contextFactory) {
|
||||
GetStorageHealthUseCase health = query -> storageHealth(query.context());
|
||||
GetRuntimeCapabilitiesUseCase runtime = query -> capabilities(query.context());
|
||||
ListOrphansUseCase orphanList = query -> orphans(query.limit(), query.context());
|
||||
ReconcileOrphansUseCase reconcile = this::reconcileOrphans;
|
||||
ReverifyFileUseCase reverifying = command -> reverify(command.fileId(), command.context());
|
||||
ForceDeleteFileUseCase forcing =
|
||||
command -> {
|
||||
forceDelete(command);
|
||||
return null;
|
||||
};
|
||||
ListIncompleteUploadsUseCase incomplete =
|
||||
query -> incompleteUploads(query.limit(), query.context());
|
||||
CleanupUploadsUseCase cleanup =
|
||||
command -> cleanupUploads(command.maxItems(), command.maxBytes(), command.context());
|
||||
return new FileserverAdminController(
|
||||
health,
|
||||
runtime,
|
||||
orphanList,
|
||||
reconcile,
|
||||
reverifying,
|
||||
forcing,
|
||||
incomplete,
|
||||
cleanup,
|
||||
contextFactory);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-10
@@ -5,18 +5,17 @@ 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.metadata.FileDescriptor;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSession;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.port.in.FinalizeUploadUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadService;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/** Records which uploads a protocol adapter decided to finalize. */
|
||||
public final class RecordingFinalizeService implements FinalizeUploadService {
|
||||
public final class RecordingFinalizeService {
|
||||
|
||||
private final List<UploadId> finalized = new CopyOnWriteArrayList<>();
|
||||
private final List<String> threads = new CopyOnWriteArrayList<>();
|
||||
@@ -30,13 +29,6 @@ public final class RecordingFinalizeService implements FinalizeUploadService {
|
||||
return List.copyOf(threads);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileView finalizeUpload(
|
||||
UploadSession session, FinalizeUploadRequest request, RequestContext context) {
|
||||
return finalizeUpload(session.uploadId(), request, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileView finalizeUpload(
|
||||
UploadId uploadId, FinalizeUploadRequest request, RequestContext context) {
|
||||
finalized.add(uploadId);
|
||||
@@ -54,4 +46,9 @@ public final class RecordingFinalizeService implements FinalizeUploadService {
|
||||
Optional.empty(),
|
||||
1));
|
||||
}
|
||||
|
||||
/** This fake as the finalize port. */
|
||||
public FinalizeUploadUseCase port() {
|
||||
return command -> finalizeUpload(command.uploadId(), command.request(), command.context());
|
||||
}
|
||||
}
|
||||
|
||||
+13
-3
@@ -6,10 +6,10 @@ import dev.caskeleton.application.fileserver.api.StorageNamespace;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.CreateUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest;
|
||||
import dev.caskeleton.application.fileserver.upload.SingleShotUploadService;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -29,7 +29,7 @@ import java.util.function.Function;
|
||||
* pass a fake that ignored the channel, so this one proves the bytes actually arrived through the
|
||||
* channel the controller handed over.
|
||||
*/
|
||||
public final class RecordingUploadService implements SingleShotUploadService {
|
||||
public final class RecordingUploadService {
|
||||
|
||||
private final List<String> receivedBodies = new ArrayList<>();
|
||||
private final List<CreateUploadRequest> requests = new ArrayList<>();
|
||||
@@ -59,7 +59,6 @@ public final class RecordingUploadService implements SingleShotUploadService {
|
||||
return List.copyOf(declaredContentLengths);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileView upload(
|
||||
CreateUploadRequest request,
|
||||
ReadableByteChannel content,
|
||||
@@ -111,4 +110,15 @@ public final class RecordingUploadService implements SingleShotUploadService {
|
||||
1);
|
||||
return FileView.of(descriptor);
|
||||
}
|
||||
|
||||
/** This fake as the single-request upload port. */
|
||||
public UploadFileUseCase port() {
|
||||
return command ->
|
||||
upload(
|
||||
command.request(),
|
||||
command.content(),
|
||||
command.contentLength(),
|
||||
command.finalizeRequest(),
|
||||
command.context());
|
||||
}
|
||||
}
|
||||
|
||||
+28
-10
@@ -17,10 +17,12 @@ import dev.caskeleton.application.fileserver.api.metadata.FileDescriptor;
|
||||
import dev.caskeleton.application.fileserver.api.security.RequestContext;
|
||||
import dev.caskeleton.application.fileserver.api.security.SanitizedFilename;
|
||||
import dev.caskeleton.application.fileserver.api.transfer.FileRepresentation;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadDescriptor;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadRequest;
|
||||
import dev.caskeleton.application.fileserver.download.ZeroCopyTransferResult;
|
||||
import dev.caskeleton.application.fileserver.port.in.DescribeFileUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase;
|
||||
import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentUseCase;
|
||||
import dev.caskeleton.application.fileserver.upload.FileView;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.channels.Channels;
|
||||
@@ -34,7 +36,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Download service backed by an in-memory immutable representation. */
|
||||
public final class StubDownloadService implements DownloadApplicationService {
|
||||
public final class StubDownloadService {
|
||||
|
||||
public static final String DIGEST = "d".repeat(64);
|
||||
public static final Instant PUBLISHED_AT = Instant.parse("2026-08-07T10:00:00Z");
|
||||
@@ -78,27 +80,24 @@ public final class StubDownloadService implements DownloadApplicationService {
|
||||
new HttpDownloadPolicy(HttpRangePolicy.unbounded(), "private, no-store", false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileView describeFile(FileId fileId, RequestContext context) {
|
||||
return FileView.of(descriptor(fileId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public DownloadDescriptor describe(DownloadRequest request, RequestContext context) {
|
||||
public DownloadDescriptor describe(FileId fileId, RequestContext context) {
|
||||
if (!state.isPubliclyReadable()) {
|
||||
throw new FileserverException(
|
||||
"file is not in a publicly readable state",
|
||||
FileserverFailureContext.forFileState(
|
||||
FileserverErrorCode.FILE_NOT_READY, request.fileId(), state, true));
|
||||
FileserverErrorCode.FILE_NOT_READY, fileId, state, true));
|
||||
}
|
||||
return new DownloadDescriptor(
|
||||
request.fileId(),
|
||||
fileId,
|
||||
new FileRepresentation(DIGEST, PUBLISHED_AT, content.length, mediaType),
|
||||
ContentKey.of("ab/cd/stub-object-000001"),
|
||||
new SanitizedFilename(filename));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadableByteChannel openContent(DownloadDescriptor descriptor, ByteRange range) {
|
||||
opened.add(range);
|
||||
int from = Math.toIntExact(range.startInclusive());
|
||||
@@ -106,7 +105,6 @@ public final class StubDownloadService implements DownloadApplicationService {
|
||||
return Channels.newChannel(new ByteArrayInputStream(Arrays.copyOfRange(content, from, to)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZeroCopyTransferResult transferContent(
|
||||
DownloadDescriptor descriptor, ByteRange range, WritableByteChannel sink) {
|
||||
return ZeroCopyTransferResult.notStarted();
|
||||
@@ -130,4 +128,24 @@ public final class StubDownloadService implements DownloadApplicationService {
|
||||
return FileId.of(
|
||||
UUID.nameUUIDFromBytes("stub-download".getBytes(java.nio.charset.StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
/** This fake as the describe port. */
|
||||
public DescribeFileUseCase describePort() {
|
||||
return query -> describeFile(query.fileId(), query.context());
|
||||
}
|
||||
|
||||
/** This fake as the prepare-download port. */
|
||||
public PrepareDownloadUseCase preparePort() {
|
||||
return query -> describe(query.fileId(), query.context());
|
||||
}
|
||||
|
||||
/** This fake as the open-content port. */
|
||||
public OpenDownloadContentUseCase openPort() {
|
||||
return query -> openContent(query.descriptor(), query.byteRange());
|
||||
}
|
||||
|
||||
/** This fake as the zero-copy transfer port. */
|
||||
public TransferDownloadContentUseCase transferPort() {
|
||||
return query -> transferContent(query.descriptor(), query.byteRange(), query.sink());
|
||||
}
|
||||
}
|
||||
|
||||
+5
-2
@@ -39,8 +39,11 @@ class TusProtocolContractTest {
|
||||
mvc =
|
||||
MockMvcBuilders.standaloneSetup(
|
||||
new TusController(
|
||||
uploads,
|
||||
finalizeService,
|
||||
uploads.createPort(),
|
||||
uploads.statusPort(),
|
||||
uploads.appendPort(),
|
||||
finalizeService.port(),
|
||||
uploads.cancelPort(),
|
||||
new TusRequestParser(TUS),
|
||||
FileserverWebFixtures.contextFactory(),
|
||||
FileserverWebFixtures.transferExecutor(),
|
||||
|
||||
@@ -2,7 +2,6 @@ plugins {
|
||||
id 'ca.spring-library'
|
||||
id 'ca.spring-config'
|
||||
id 'java-test-fixtures'
|
||||
id 'ca.auxiliary-source-set'
|
||||
}
|
||||
|
||||
// Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001.
|
||||
@@ -50,22 +49,39 @@ tasks.named('test') {
|
||||
// The web platform's reusable ArchUnit rules ship in their own source set, consumed by this leaf's
|
||||
// tests and by the composition root. A rule pack that only its own fixture tests import is verified
|
||||
// as library code and applied to nothing — the shape the JPA testkit had to be corrected out of.
|
||||
auxiliarySourceSets {
|
||||
sourceSet('systemTest') {
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
}
|
||||
sourceSet('performanceTest') {
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
}
|
||||
// The Jetty compatibility lane is its own source set because it needs a different embedded
|
||||
// server on the classpath. Two servers in one source set means Spring Boot picks one and the
|
||||
// "Jetty" lane silently runs on Tomcat — a compatibility matrix that certifies the same
|
||||
// container twice.
|
||||
sourceSet('jettyCompatTest') {
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
inherits 'implementation'
|
||||
testing {
|
||||
suites {
|
||||
systemTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
performanceTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
// The Jetty compatibility lane is its own source set because it needs a different embedded
|
||||
// server on the classpath. Two servers in one source set means Spring Boot picks one and the
|
||||
// "Jetty" lane silently runs on Tomcat — a compatibility matrix that certifies the same
|
||||
// container twice.
|
||||
jettyCompatTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
configurations {
|
||||
systemTestImplementation.extendsFrom testImplementation
|
||||
systemTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
performanceTestImplementation.extendsFrom testImplementation
|
||||
performanceTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
jettyCompatTestImplementation.extendsFrom testImplementation
|
||||
}
|
||||
|
||||
// ArchUnit is declared after the testkit source set exists, because `testFixturesImplementation` is
|
||||
// created by that declaration.
|
||||
|
||||
@@ -2,7 +2,6 @@ plugins {
|
||||
id 'ca.spring-library'
|
||||
id 'ca.spring-config'
|
||||
id 'java-test-fixtures'
|
||||
id 'ca.auxiliary-source-set'
|
||||
}
|
||||
|
||||
// Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001.
|
||||
@@ -29,25 +28,41 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
}
|
||||
|
||||
auxiliarySourceSets {
|
||||
sourceSet('systemTest') {
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
}
|
||||
// Jetty replaces Tomcat for this lane only. With both on one classpath Boot starts Tomcat and
|
||||
// the lane certifies the same container twice — which for a WebSocket matters more than for
|
||||
// HTTP, because upgrade handling, close-frame timing and idle handling are all container code.
|
||||
// The proxy lane runs the platform behind a real Nginx. Its own source set because it is the
|
||||
// only lane that needs Docker; folded into `test`, every developer's `check` would depend on a
|
||||
// container runtime and the usual end of that is a disabled test nobody notices.
|
||||
sourceSet('nginxWebSocketTest') {
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
inherits 'implementation'
|
||||
}
|
||||
sourceSet('jettyWebSocketTest') {
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
inherits 'implementation'
|
||||
testing {
|
||||
suites {
|
||||
systemTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
// Jetty replaces Tomcat for the jetty lane only. With both on one classpath Boot starts
|
||||
// Tomcat and the lane certifies the same container twice — which for a WebSocket matters
|
||||
// more than for HTTP, because upgrade handling, close-frame timing and idle handling are
|
||||
// all container code. The proxy lane runs the platform behind a real Nginx. Its own source
|
||||
// set because it is the only lane that needs Docker; folded into `test`, every developer's
|
||||
// `check` would depend on a container runtime and the usual end of that is a disabled test
|
||||
// nobody notices.
|
||||
nginxWebSocketTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
jettyWebSocketTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
configurations {
|
||||
systemTestImplementation.extendsFrom testImplementation
|
||||
systemTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
nginxWebSocketTestImplementation.extendsFrom testImplementation
|
||||
jettyWebSocketTestImplementation.extendsFrom testImplementation
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Declared rather than inherited: the `testkit` source set extended testImplementation, so the
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ import org.slf4j.LoggerFactory;
|
||||
* logged at the same level as a successful one: a refused force-delete is the entry a reviewer most
|
||||
* needs to find.
|
||||
*/
|
||||
public final class StructuredAdminAuditAdapter implements AdminAuditPort {
|
||||
public final class StructuredAdminAudit implements AdminAuditPort {
|
||||
|
||||
private static final Logger AUDIT = LoggerFactory.getLogger("dev.caskeleton.fileserver.audit");
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ import org.slf4j.LoggerFactory;
|
||||
* file needs the operator action and the user action interleaved in one ordered stream, not
|
||||
* correlated across two sinks after the fact.
|
||||
*/
|
||||
public final class StructuredFileserverAuditAdapter implements FileserverAuditPort {
|
||||
public final class StructuredFileserverAudit implements FileserverAuditPort {
|
||||
|
||||
private static final Logger AUDIT = LoggerFactory.getLogger("dev.caskeleton.fileserver.audit");
|
||||
|
||||
-1
@@ -43,7 +43,6 @@ import org.springframework.core.env.Environment;
|
||||
FileserverStorageOperationsConfiguration.class,
|
||||
FileserverVerificationConfiguration.class,
|
||||
FileserverSecurityConfiguration.class,
|
||||
FileserverDownloadLifecycleConfiguration.class,
|
||||
FileserverMaintenanceServiceConfiguration.class
|
||||
})
|
||||
public class FileserverCapabilityAutoConfiguration {
|
||||
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort;
|
||||
import dev.caskeleton.application.fileserver.download.DefaultDownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadContentPort;
|
||||
import dev.caskeleton.application.fileserver.download.ZeroCopyDownloadPort;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.CopyContentPort;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.DefaultFileLifecycleService;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.FileLifecycleService;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverDownloadLifecycleConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
DownloadApplicationService fileserverDownloadService(
|
||||
FileMetadataPort metadataStore,
|
||||
DownloadContentPort contentGateway,
|
||||
FileAccessPolicyPort accessPolicy,
|
||||
ZeroCopyDownloadPort zeroCopyGateway,
|
||||
ObjectProvider<FileserverMetricsPort> metrics) {
|
||||
return new DefaultDownloadApplicationService(
|
||||
metadataStore,
|
||||
contentGateway,
|
||||
accessPolicy,
|
||||
Optional.of(zeroCopyGateway),
|
||||
FileserverMetricsSupport.metricsOrNoop(metrics));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileLifecycleService fileserverLifecycleService(
|
||||
FileMetadataPort metadataStore,
|
||||
CopyContentPort copyGateway,
|
||||
FileAccessPolicyPort accessPolicy,
|
||||
OriginalFilenamePolicy filenamePolicy,
|
||||
CleanupQueuePort cleanupQueue,
|
||||
UploadSessionPort sessionStore,
|
||||
StagingUploadLocatorPort stagingLocator,
|
||||
UploadIdentifierPort identifierFactory,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultFileLifecycleService(
|
||||
metadataStore,
|
||||
copyGateway,
|
||||
accessPolicy,
|
||||
filenamePolicy,
|
||||
cleanupQueue,
|
||||
sessionStore,
|
||||
stagingLocator,
|
||||
identifierFactory,
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
}
|
||||
-48
@@ -1,20 +1,13 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure;
|
||||
|
||||
import dev.caskeleton.application.fileserver.admin.AdminAuditPort;
|
||||
import dev.caskeleton.application.fileserver.admin.DefaultFileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.FileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupContentPort;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupService;
|
||||
import dev.caskeleton.application.fileserver.cleanup.DefaultCleanupService;
|
||||
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint;
|
||||
import dev.caskeleton.application.fileserver.recovery.DefaultFileReconciliationService;
|
||||
import dev.caskeleton.application.fileserver.recovery.FileReconciliationService;
|
||||
import dev.caskeleton.application.fileserver.recovery.ReconciliationContentPort;
|
||||
@@ -25,7 +18,6 @@ import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -77,44 +69,4 @@ class FileserverMaintenanceServiceConfiguration {
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
|
||||
/**
|
||||
* The management plane, gated on its own switch.
|
||||
*
|
||||
* <p>Admin is a separate decision from the data plane: a deployment that serves files does not
|
||||
* automatically want an endpoint that can force-delete them.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform.admin",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
FileserverAdminService fileserverAdminService(
|
||||
StorageHealthPort healthPort,
|
||||
OrphanScanPort orphanScanPort,
|
||||
FileMetadataPort metadataStore,
|
||||
UploadSessionPort sessionStore,
|
||||
StagingUploadLocatorPort stagingLocator,
|
||||
CleanupQueuePort cleanupQueue,
|
||||
CleanupService cleanupService,
|
||||
FileAccessPolicyPort accessPolicy,
|
||||
AdminAuditPort auditPort,
|
||||
SafeFileFingerprint fingerprint,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultFileserverAdminService(
|
||||
healthPort,
|
||||
orphanScanPort,
|
||||
metadataStore,
|
||||
sessionStore,
|
||||
stagingLocator,
|
||||
cleanupQueue,
|
||||
cleanupService,
|
||||
accessPolicy,
|
||||
auditPort,
|
||||
fingerprint,
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.audit.StructuredAdminAuditAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.audit.StructuredFileserverAuditAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.audit.StructuredAdminAudit;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.audit.StructuredFileserverAudit;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.RoleBasedFileAccessPolicy;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.UnenforcedFileAccessPolicy;
|
||||
import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException;
|
||||
@@ -69,13 +69,13 @@ public class FileserverSecurityConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
AdminAuditPort fileserverAdminAudit() {
|
||||
return new StructuredAdminAuditAdapter();
|
||||
return new StructuredAdminAudit();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverAuditPort fileserverAccessAudit() {
|
||||
return new StructuredFileserverAuditAdapter();
|
||||
return new StructuredFileserverAudit();
|
||||
}
|
||||
|
||||
private static FileAccessPolicyPort unenforcedOrFail(Environment environment) {
|
||||
|
||||
+8
-8
@@ -1,10 +1,10 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalCleanupContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalCopyContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadStorageGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalCleanupContent;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalCopyContent;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadContent;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadStorage;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort;
|
||||
@@ -22,7 +22,7 @@ class FileserverStorageGatewayConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
UploadStoragePort fileserverUploadStorageGateway(LocalBlockingContentStore store) {
|
||||
return new LocalUploadStorageGateway(store);
|
||||
return new LocalUploadStorage(store);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -32,7 +32,7 @@ class FileserverStorageGatewayConfiguration {
|
||||
FileMetadataPort metadataStore,
|
||||
UploadSessionPort sessionStore,
|
||||
FileserverPlatformSettings settings) {
|
||||
return new LocalUploadContentGateway(
|
||||
return new LocalUploadContent(
|
||||
store, metadataStore, sessionStore, settings.upload().maxFileSize().toBytes());
|
||||
}
|
||||
|
||||
@@ -40,13 +40,13 @@ class FileserverStorageGatewayConfiguration {
|
||||
@ConditionalOnMissingBean
|
||||
CopyContentPort fileserverCopyContentGateway(
|
||||
LocalBlockingContentStore store, FileserverPlatformSettings settings) {
|
||||
return new LocalCopyContentGateway(store, settings.upload().maxFileSize().toBytes());
|
||||
return new LocalCopyContent(store, settings.upload().maxFileSize().toBytes());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
CleanupContentPort fileserverCleanupContentGateway(
|
||||
LocalBlockingContentStore store, OrphanScanPort orphans) {
|
||||
return new LocalCleanupContentGateway(store, orphans);
|
||||
return new LocalCleanupContent(store, orphans);
|
||||
}
|
||||
}
|
||||
|
||||
+8
-9
@@ -1,12 +1,12 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalOrphanScanAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalReconciliationContentProbe;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageHealthAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalOrphanScan;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalReconciliationContent;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageHealth;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProperties;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageUsageProbe;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageUsage;
|
||||
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthPort;
|
||||
@@ -27,7 +27,7 @@ class FileserverStorageOperationsConfiguration {
|
||||
LocalStorageProperties properties,
|
||||
LocalStorageProbeResult probeResult,
|
||||
LocalBlockingContentStore store) {
|
||||
return new LocalStorageHealthAdapter(properties, probeResult, store);
|
||||
return new LocalStorageHealth(properties, probeResult, store);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -37,20 +37,19 @@ class FileserverStorageOperationsConfiguration {
|
||||
LocalStorageProperties properties,
|
||||
FileserverPlatformSettings settings,
|
||||
Clock clock) {
|
||||
return new LocalOrphanScanAdapter(
|
||||
ledger, properties, settings.admin().orphanMinimumAge(), clock);
|
||||
return new LocalOrphanScan(ledger, properties, settings.admin().orphanMinimumAge(), clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
StorageUsagePort fileserverStorageUsageProbe(LocalStorageProperties properties) {
|
||||
return new LocalStorageUsageProbe(properties.root());
|
||||
return new LocalStorageUsage(properties.root());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
ReconciliationContentPort fileserverReconciliationProbe(
|
||||
LocalBlockingContentStore store, StagingUploadLocatorPort stagingLocator) {
|
||||
return new LocalReconciliationContentProbe(store, stagingLocator);
|
||||
return new LocalReconciliationContent(store, stagingLocator);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.FileVerifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.FilenamePolicyVerifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.LengthVerifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.LocalVerificationContentReader;
|
||||
@@ -9,7 +10,6 @@ import dev.caskeleton.adapter.outbound.fileserver.platform.verification.Scriptab
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.Sha256Verifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.VerificationContentReader;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.VerificationCoordinator;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.upload.FileVerificationPort;
|
||||
import java.util.List;
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import java.util.UUID;
|
||||
* <p>{@link UUID#randomUUID()} is backed by a seeded {@code SecureRandom} and is safe to share
|
||||
* across threads.
|
||||
*/
|
||||
public final class RandomUploadIdentifierFactory implements UploadIdentifierPort {
|
||||
public final class RandomUploadIdentifier implements UploadIdentifierPort {
|
||||
|
||||
@Override
|
||||
public FileId newFileId() {
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureDirectoryWalk;
|
||||
import dev.caskeleton.application.fileserver.api.ContentKey;
|
||||
import dev.caskeleton.application.fileserver.api.content.FinalizeContentCommand;
|
||||
import dev.caskeleton.application.fileserver.api.error.AmbiguousCompletionException;
|
||||
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureDirectoryWalk;
|
||||
import dev.caskeleton.application.fileserver.api.content.FinalizeContentCommand;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
|
||||
+2
-2
@@ -14,12 +14,12 @@ import dev.caskeleton.application.fileserver.cleanup.CleanupContentPort;
|
||||
* deleting, and the store refuses the delete when the object on disk disagrees. Dropping the
|
||||
* precondition here would turn every stale queue entry into a live-data delete.
|
||||
*/
|
||||
public final class LocalCleanupContentGateway implements CleanupContentPort {
|
||||
public final class LocalCleanupContent implements CleanupContentPort {
|
||||
|
||||
private final LocalBlockingContentStore store;
|
||||
private final OrphanScanPort orphans;
|
||||
|
||||
public LocalCleanupContentGateway(LocalBlockingContentStore store, OrphanScanPort orphans) {
|
||||
public LocalCleanupContent(LocalBlockingContentStore store, OrphanScanPort orphans) {
|
||||
this.store = store;
|
||||
this.orphans = orphans;
|
||||
}
|
||||
+3
-4
@@ -28,18 +28,17 @@ import java.util.UUID;
|
||||
* <p>A failed copy takes its staging object with it, because an abandoned partial copy has no
|
||||
* record pointing at it and would otherwise only ever be found by an orphan scan.
|
||||
*/
|
||||
public final class LocalCopyContentGateway implements CopyContentPort {
|
||||
public final class LocalCopyContent implements CopyContentPort {
|
||||
|
||||
private final LocalBlockingContentStore store;
|
||||
private final long maximumFileSize;
|
||||
private final SecureRandom random;
|
||||
|
||||
public LocalCopyContentGateway(LocalBlockingContentStore store, long maximumFileSize) {
|
||||
public LocalCopyContent(LocalBlockingContentStore store, long maximumFileSize) {
|
||||
this(store, maximumFileSize, new SecureRandom());
|
||||
}
|
||||
|
||||
LocalCopyContentGateway(
|
||||
LocalBlockingContentStore store, long maximumFileSize, SecureRandom random) {
|
||||
LocalCopyContent(LocalBlockingContentStore store, long maximumFileSize, SecureRandom random) {
|
||||
if (maximumFileSize <= 0) {
|
||||
throw new IllegalArgumentException("maximumFileSize must be positive");
|
||||
}
|
||||
+2
-2
@@ -39,7 +39,7 @@ import java.util.stream.Stream;
|
||||
* <p>Third, the delete still carries a size precondition, so even a matching fingerprint cannot
|
||||
* remove an object whose length no longer agrees with what was observed.
|
||||
*/
|
||||
public final class LocalOrphanScanAdapter implements OrphanScanPort {
|
||||
public final class LocalOrphanScan implements OrphanScanPort {
|
||||
|
||||
private static final int MAXIMUM_WALK_DEPTH = 4;
|
||||
|
||||
@@ -48,7 +48,7 @@ public final class LocalOrphanScanAdapter implements OrphanScanPort {
|
||||
private final Duration minimumAge;
|
||||
private final Clock clock;
|
||||
|
||||
public LocalOrphanScanAdapter(
|
||||
public LocalOrphanScan(
|
||||
ContentReferenceLedgerPort ledger,
|
||||
LocalStorageProperties properties,
|
||||
Duration minimumAge,
|
||||
+2
-2
@@ -19,12 +19,12 @@ import java.util.Optional;
|
||||
* exists, and reporting either as absence would have reconciliation quarantine intact files or
|
||||
* declare a completed publish not-applied.
|
||||
*/
|
||||
public final class LocalReconciliationContentProbe implements ReconciliationContentPort {
|
||||
public final class LocalReconciliationContent implements ReconciliationContentPort {
|
||||
|
||||
private final LocalBlockingContentStore store;
|
||||
private final StagingUploadLocatorPort stagingLocator;
|
||||
|
||||
public LocalReconciliationContentProbe(
|
||||
public LocalReconciliationContent(
|
||||
LocalBlockingContentStore store, StagingUploadLocatorPort stagingLocator) {
|
||||
this.store = store;
|
||||
this.stagingLocator = stagingLocator;
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureDirectoryWalk;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
|
||||
+17
@@ -1,5 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureDirectoryWalk;
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureFileAccess;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileAlreadyExistsException;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileNotFoundException;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
|
||||
@@ -17,6 +19,16 @@ final class LocalStorageFailures {
|
||||
private LocalStorageFailures() {}
|
||||
|
||||
static FileserverException translate(IOException exception) {
|
||||
// The descriptor walk's own refusals first. They are permanent path rejections, and the
|
||||
// classifier below would read the platform's generic exception as an unavailable volume — a
|
||||
// retryable 503 that a client would retry into a link that now points somewhere else.
|
||||
if (exception instanceof SecureDirectoryWalk.SymbolicComponentException) {
|
||||
return pathRejected("a storage path component is a symbolic link");
|
||||
}
|
||||
if (exception instanceof SecureFileAccess.NotRegularFileException
|
||||
|| exception instanceof SecureDirectoryWalk.PathEscapeException) {
|
||||
return pathRejected("storage target is not a regular file below the storage root");
|
||||
}
|
||||
FileserverErrorCode code = FilesystemFailureClassifier.classify(exception);
|
||||
return switch (code) {
|
||||
case FILE_ALREADY_EXISTS ->
|
||||
@@ -42,4 +54,9 @@ final class LocalStorageFailures {
|
||||
FileserverFailureContext.of(FileserverErrorCode.STORAGE_UNAVAILABLE, true));
|
||||
};
|
||||
}
|
||||
|
||||
private static FileserverException pathRejected(String message) {
|
||||
return new FileserverException(
|
||||
message, FileserverFailureContext.of(FileserverErrorCode.PATH_OUTSIDE_NAMESPACE, false));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -21,13 +21,13 @@ import java.util.List;
|
||||
* configured. Configuration states an intent; the probe states a fact, and only the fact is safe to
|
||||
* publish as a capability.
|
||||
*/
|
||||
public final class LocalStorageHealthAdapter implements StorageHealthPort {
|
||||
public final class LocalStorageHealth implements StorageHealthPort {
|
||||
|
||||
private final LocalStorageProperties properties;
|
||||
private final LocalStorageProbeResult probeResult;
|
||||
private final LocalBlockingContentStore store;
|
||||
|
||||
public LocalStorageHealthAdapter(
|
||||
public LocalStorageHealth(
|
||||
LocalStorageProperties properties,
|
||||
LocalStorageProbeResult probeResult,
|
||||
LocalBlockingContentStore store) {
|
||||
+2
-2
@@ -18,11 +18,11 @@ import java.util.OptionalDouble;
|
||||
* synthetic 0% would silently disable the high-water guard, and a synthetic 100% would take the
|
||||
* capability down over a failed syscall.
|
||||
*/
|
||||
public final class LocalStorageUsageProbe implements StorageUsagePort {
|
||||
public final class LocalStorageUsage implements StorageUsagePort {
|
||||
|
||||
private final Path root;
|
||||
|
||||
public LocalStorageUsageProbe(Path root) {
|
||||
public LocalStorageUsage(Path root) {
|
||||
if (!root.isAbsolute()) {
|
||||
throw new IllegalArgumentException("storage root must be absolute");
|
||||
}
|
||||
+2
-2
@@ -25,14 +25,14 @@ import java.util.OptionalLong;
|
||||
* the authoritative record rather than guessed from configuration: a file created under one
|
||||
* namespace must finalize under that same namespace even if the default has since changed.
|
||||
*/
|
||||
public final class LocalUploadContentGateway implements UploadContentPort {
|
||||
public final class LocalUploadContent implements UploadContentPort {
|
||||
|
||||
private final LocalBlockingContentStore store;
|
||||
private final FileMetadataPort metadataStore;
|
||||
private final UploadSessionPort sessionStore;
|
||||
private final long maximumFileSize;
|
||||
|
||||
public LocalUploadContentGateway(
|
||||
public LocalUploadContent(
|
||||
LocalBlockingContentStore store,
|
||||
FileMetadataPort metadataStore,
|
||||
UploadSessionPort sessionStore,
|
||||
+2
-2
@@ -19,11 +19,11 @@ import java.util.OptionalLong;
|
||||
* belongs to the store; repeating any of it here would give the capability two answers to the same
|
||||
* question.
|
||||
*/
|
||||
public final class LocalUploadStorageGateway implements UploadStoragePort {
|
||||
public final class LocalUploadStorage implements UploadStoragePort {
|
||||
|
||||
private final LocalBlockingContentStore store;
|
||||
|
||||
public LocalUploadStorageGateway(LocalBlockingContentStore store) {
|
||||
public LocalUploadStorage(LocalBlockingContentStore store) {
|
||||
this.store = store;
|
||||
}
|
||||
|
||||
+32
-194
@@ -1,53 +1,32 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureFileAccess;
|
||||
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 java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SecureDirectoryStream;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.PosixFileAttributeView;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Opens local files through directory descriptors, never through a re-resolved pathname.
|
||||
* The Fileserver's face of the shared descriptor-relative file primitive.
|
||||
*
|
||||
* <p>The previous shape proved that no component below the root was a symbolic link and then called
|
||||
* {@code FileChannel.open} on the full path. Those are two independent lookups: a directory
|
||||
* replaced between them is followed by the second one, and no amount of additional checking closes
|
||||
* that window — it only moves it. Every open, delete and stat here instead descends one directory
|
||||
* at a time with {@code NOFOLLOW_LINKS}, and performs the final operation relative to the innermost
|
||||
* descriptor, so what was verified and what is used are the same object.
|
||||
* <p>The primitive itself — descend one directory at a time with {@code NOFOLLOW_LINKS} and act
|
||||
* relative to the innermost descriptor, so what was verified and what is used are the same object —
|
||||
* is {@link SecureFileAccess} in {@code adapter:outbound:support}, where object storage's local
|
||||
* provider can use the same one. What stays here is the translation into the Fileserver's failure
|
||||
* vocabulary: a symbolic component or a non-regular leaf is a permanent {@code
|
||||
* PATH_OUTSIDE_NAMESPACE}, never a retryable storage outage, and every other filesystem failure
|
||||
* goes through {@link LocalStorageFailures}.
|
||||
*
|
||||
* <p>{@code failOnSymlink} remains as a constructor argument for the probe and for tests that
|
||||
* deliberately exercise a permissive profile. In the production profile it is pinned on, and with
|
||||
* descriptor-relative access the refusal is structural rather than advisory: a symlinked component
|
||||
* cannot be descended into at all.
|
||||
* <p>{@code failOnSymlink} remains for the capability probe, which still reasons about pathnames,
|
||||
* and for tests that exercise a permissive profile. Descriptor-relative access refuses a symlinked
|
||||
* component by construction whatever it says.
|
||||
*/
|
||||
final class SafeFileChannelFactory {
|
||||
|
||||
private static final Set<PosixFilePermission> OWNER_ONLY_FILE =
|
||||
PosixFilePermissions.fromString("rw-------");
|
||||
private static final Set<PosixFilePermission> OWNER_ONLY_DIRECTORY =
|
||||
PosixFilePermissions.fromString("rwx------");
|
||||
|
||||
private static final Set<OpenOption> CREATE_NEW_OPTIONS =
|
||||
Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
|
||||
private static final Set<OpenOption> WRITE_OPTIONS =
|
||||
Set.of(StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS);
|
||||
private static final Set<OpenOption> READ_OPTIONS =
|
||||
Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS);
|
||||
|
||||
private final boolean failOnSymlink;
|
||||
|
||||
SafeFileChannelFactory(boolean failOnSymlink) {
|
||||
@@ -56,99 +35,40 @@ final class SafeFileChannelFactory {
|
||||
|
||||
/** Creates a brand-new zero-length file; an existing target is a conflict, never an overwrite. */
|
||||
FileChannel createNew(Path root, Path target) {
|
||||
createParentDirectories(root, target);
|
||||
return inParent(
|
||||
root,
|
||||
target,
|
||||
(directory, leaf) -> {
|
||||
FileChannel channel =
|
||||
requireFileChannel(
|
||||
directory.newByteChannel(
|
||||
leaf,
|
||||
CREATE_NEW_OPTIONS,
|
||||
PosixFilePermissions.asFileAttribute(OWNER_ONLY_FILE)));
|
||||
// Anything that fails after the file exists must not also leak its descriptor. The
|
||||
// previous version applied permissions and re-checked the type after opening, and threw
|
||||
// both without closing.
|
||||
try {
|
||||
applyOwnerOnlyPermissions(directory, leaf);
|
||||
requireRegularFile(directory, leaf);
|
||||
return channel;
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
closeQuietly(channel);
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
return translated(() -> SecureFileAccess.createNew(root, target));
|
||||
}
|
||||
|
||||
/** Opens an existing file for append; the file must already be a regular non-link file. */
|
||||
FileChannel openForWrite(Path root, Path target) {
|
||||
return inParent(
|
||||
root,
|
||||
target,
|
||||
(directory, leaf) -> {
|
||||
requireRegularFile(directory, leaf);
|
||||
return requireFileChannel(directory.newByteChannel(leaf, WRITE_OPTIONS));
|
||||
});
|
||||
return translated(() -> SecureFileAccess.openForWrite(root, target));
|
||||
}
|
||||
|
||||
/** Opens an existing file for reading, refusing anything that is not a regular file. */
|
||||
FileChannel openForRead(Path root, Path target) {
|
||||
return inParent(
|
||||
root,
|
||||
target,
|
||||
(directory, leaf) -> {
|
||||
requireRegularFile(directory, leaf);
|
||||
return requireFileChannel(directory.newByteChannel(leaf, READ_OPTIONS));
|
||||
});
|
||||
return translated(() -> SecureFileAccess.openForRead(root, target));
|
||||
}
|
||||
|
||||
/** Deletes a regular file relative to its verified parent; absence is not an error. */
|
||||
boolean deleteRegularFile(Path root, Path target) {
|
||||
return inParent(
|
||||
root,
|
||||
target,
|
||||
(directory, leaf) -> {
|
||||
try {
|
||||
requireRegularFile(directory, leaf);
|
||||
directory.deleteFile(leaf);
|
||||
return true;
|
||||
} catch (NoSuchFileException alreadyGone) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return translated(() -> SecureFileAccess.deleteRegularFile(root, target));
|
||||
}
|
||||
|
||||
/** Reads attributes without following a link, or empty when the object is not there. */
|
||||
/** Reads attributes without following a link. */
|
||||
BasicFileAttributes readAttributes(Path root, Path target) {
|
||||
return inParent(root, target, (directory, leaf) -> attributesOf(directory, leaf));
|
||||
return translated(() -> SecureFileAccess.readAttributes(root, target));
|
||||
}
|
||||
|
||||
/** True when a regular, non-symbolic file exists at {@code target}. */
|
||||
boolean isRegularFile(Path root, Path target) {
|
||||
return inParent(
|
||||
root,
|
||||
target,
|
||||
(directory, leaf) -> {
|
||||
try {
|
||||
return attributesOf(directory, leaf).isRegularFile();
|
||||
} catch (NoSuchFileException absent) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return translated(() -> SecureFileAccess.isRegularFile(root, target));
|
||||
}
|
||||
|
||||
void createParentDirectories(Path root, Path target) {
|
||||
Path parent = target.getParent();
|
||||
if (parent == null || Files.isDirectory(parent, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(parent);
|
||||
applyOwnerOnlyDirectoryPermissions(root, parent);
|
||||
} catch (IOException exception) {
|
||||
throw translate(exception);
|
||||
}
|
||||
translated(
|
||||
() -> {
|
||||
SecureFileAccess.createParentDirectories(root, target);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,102 +95,20 @@ final class SafeFileChannelFactory {
|
||||
}
|
||||
}
|
||||
|
||||
/** Type check performed through the parent descriptor, so it names the object that was opened. */
|
||||
private void requireRegularFile(SecureDirectoryStream<Path> directory, Path leaf)
|
||||
throws IOException {
|
||||
BasicFileAttributes attributes;
|
||||
/** One filesystem step whose failure is translated into the Fileserver vocabulary. */
|
||||
@FunctionalInterface
|
||||
private interface FileStep<T> {
|
||||
T run() throws IOException;
|
||||
}
|
||||
|
||||
private static <T> T translated(FileStep<T> step) {
|
||||
try {
|
||||
attributes = attributesOf(directory, leaf);
|
||||
} catch (NoSuchFileException absent) {
|
||||
return;
|
||||
}
|
||||
if (attributes.isSymbolicLink()) {
|
||||
throw symlinkRejected();
|
||||
}
|
||||
if (!attributes.isRegularFile()) {
|
||||
throw new FileserverException(
|
||||
"storage target is not a regular file",
|
||||
FileserverFailureContext.of(FileserverErrorCode.PATH_OUTSIDE_NAMESPACE, false));
|
||||
}
|
||||
}
|
||||
|
||||
private static BasicFileAttributes attributesOf(SecureDirectoryStream<Path> directory, Path leaf)
|
||||
throws IOException {
|
||||
return directory
|
||||
.getFileAttributeView(leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
|
||||
.readAttributes();
|
||||
}
|
||||
|
||||
private void applyOwnerOnlyPermissions(SecureDirectoryStream<Path> directory, Path leaf)
|
||||
throws IOException {
|
||||
PosixFileAttributeView view =
|
||||
directory.getFileAttributeView(
|
||||
leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
|
||||
if (view == null) {
|
||||
return;
|
||||
}
|
||||
view.setPermissions(OWNER_ONLY_FILE);
|
||||
}
|
||||
|
||||
private void applyOwnerOnlyDirectoryPermissions(Path root, Path leaf) {
|
||||
if (!supportsPosix(leaf)) {
|
||||
return;
|
||||
}
|
||||
Path relative = root.relativize(leaf);
|
||||
Path current = root;
|
||||
for (Path segment : relative) {
|
||||
current = current.resolve(segment);
|
||||
try {
|
||||
Files.setPosixFilePermissions(current, OWNER_ONLY_DIRECTORY);
|
||||
} catch (IOException exception) {
|
||||
throw translate(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The storage engine needs a {@link FileChannel}, not any seekable channel.
|
||||
*
|
||||
* <p>Positional reads, {@code truncate} for the append rollback, {@code force} for durability and
|
||||
* {@code transferTo} for zero copy are all {@code FileChannel} operations. Every platform that
|
||||
* offers {@link SecureDirectoryStream} returns one here; a platform that did not would have to be
|
||||
* refused rather than silently degraded, since the alternative is losing the rollback.
|
||||
*/
|
||||
private static FileChannel requireFileChannel(SeekableByteChannel channel) throws IOException {
|
||||
if (channel instanceof FileChannel fileChannel) {
|
||||
return fileChannel;
|
||||
}
|
||||
closeQuietly(channel);
|
||||
throw new IOException(
|
||||
"secure directory stream did not yield a FileChannel; positional write, truncate and "
|
||||
+ "force are required and cannot be emulated");
|
||||
}
|
||||
|
||||
/** Bridges the checked-exception walk into the Fileserver failure vocabulary. */
|
||||
private <T> T inParent(Path root, Path target, SecureDirectoryWalk.LeafOperation<T> operation) {
|
||||
try {
|
||||
return SecureDirectoryWalk.inParentOf(root, target, operation);
|
||||
} catch (SecureDirectoryWalk.SymbolicComponentException symlinked) {
|
||||
// A permanent path rejection, not a storage outage: it must not be answered as a retryable
|
||||
// 503, and it must never be retried into a link that now points somewhere else.
|
||||
throw symlinkRejected();
|
||||
return step.run();
|
||||
} catch (IOException exception) {
|
||||
throw translate(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean supportsPosix(Path target) {
|
||||
return target.getFileSystem().supportedFileAttributeViews().contains("posix");
|
||||
}
|
||||
|
||||
private static void closeQuietly(AutoCloseable channel) {
|
||||
try {
|
||||
channel.close();
|
||||
} catch (Exception ignored) {
|
||||
// The caller is already failing; a close failure must not mask the original cause.
|
||||
}
|
||||
}
|
||||
|
||||
private static FileserverException symlinkRejected() {
|
||||
return new FileserverException(
|
||||
"a storage path component is a symbolic link",
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationVerdict;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
* One step of the verification pipeline {@link VerificationCoordinator} runs.
|
||||
*
|
||||
* <p>The application sees only {@code FileVerificationPort}; which steps make up the pipeline is
|
||||
* this adapter's own business, so the step type lives here rather than in the application API.
|
||||
*
|
||||
* <p>A verifier returns only a stable code and bounded safe metadata. It never logs a content
|
||||
* sample, and a failure to reach an external scanner is {@link VerificationVerdict#RETRY}, never
|
||||
* {@link VerificationVerdict#ACCEPT}.
|
||||
*/
|
||||
public interface FileVerifier {
|
||||
|
||||
String verifierId();
|
||||
|
||||
CompletionStage<VerificationResult> verify(VerificationRequest request);
|
||||
}
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
import java.util.List;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.verification;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationResult;
|
||||
import dev.caskeleton.application.fileserver.upload.FileVerificationPort;
|
||||
|
||||
+8
-8
@@ -32,7 +32,7 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
* failure mode that matters: a scan that misses an orphan wastes disk, a scan that names a live
|
||||
* object loses a file.
|
||||
*/
|
||||
class LocalOrphanScanAdapterTest {
|
||||
class LocalOrphanScanTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-08-08T12:00:00Z");
|
||||
private static final Duration GRACE = Duration.ofHours(1);
|
||||
@@ -87,7 +87,7 @@ class LocalOrphanScanAdapterTest {
|
||||
@Test
|
||||
void retiringWithTheObservedFingerprintTakesTheObjectOutOfService() {
|
||||
StoredContent published = publish("reclaim me");
|
||||
LocalOrphanScanAdapter scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
LocalOrphanScan scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
OrphanObject orphan = scanner.scan(10).get(0);
|
||||
|
||||
assertThat(scanner.deleteIfFingerprintMatches(orphan.contentKey(), orphan.fingerprint()))
|
||||
@@ -104,7 +104,7 @@ class LocalOrphanScanAdapterTest {
|
||||
@Test
|
||||
void anObjectClaimedWhileItIsBeingRetiredIsPutBack() {
|
||||
StoredContent published = publish("adopted mid-flight");
|
||||
LocalOrphanScanAdapter scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
LocalOrphanScan scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
OrphanObject orphan = scanner.scan(10).get(0);
|
||||
// The ledger starts unreferenced and becomes referenced on its second consultation, which is
|
||||
// exactly the interleaving a check-then-unlink cannot survive.
|
||||
@@ -119,7 +119,7 @@ class LocalOrphanScanAdapterTest {
|
||||
@Test
|
||||
void aQuarantinedObjectIsPurgedOnlyWhileNothingReferencesIt() {
|
||||
StoredContent published = publish("purge me");
|
||||
LocalOrphanScanAdapter scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
LocalOrphanScan scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
OrphanObject orphan = scanner.scan(10).get(0);
|
||||
scanner.deleteIfFingerprintMatches(orphan.contentKey(), orphan.fingerprint());
|
||||
|
||||
@@ -133,7 +133,7 @@ class LocalOrphanScanAdapterTest {
|
||||
@Test
|
||||
void deletingWithAStaleFingerprintIsRefused() {
|
||||
StoredContent published = publish("protected");
|
||||
LocalOrphanScanAdapter scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
LocalOrphanScan scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
|
||||
assertThat(scanner.deleteIfFingerprintMatches(published.contentKey(), "not-what-was-seen"))
|
||||
.isFalse();
|
||||
@@ -143,7 +143,7 @@ class LocalOrphanScanAdapterTest {
|
||||
@Test
|
||||
void anObjectThatGainedARecordBetweenScanAndApplyIsNoLongerDeletable() {
|
||||
StoredContent published = publish("adopted");
|
||||
LocalOrphanScanAdapter scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
LocalOrphanScan scanner = scanner(NOW.plus(Duration.ofDays(1)));
|
||||
OrphanObject orphan = scanner.scan(10).get(0);
|
||||
|
||||
referenced.add(published.contentKey().value());
|
||||
@@ -168,7 +168,7 @@ class LocalOrphanScanAdapterTest {
|
||||
|
||||
private String claimAfterFirstLookup;
|
||||
|
||||
private LocalOrphanScanAdapter scanner(Instant now) {
|
||||
private LocalOrphanScan scanner(Instant now) {
|
||||
ContentReferenceLedgerPort ledger =
|
||||
key -> {
|
||||
if (key.value().equals(claimAfterFirstLookup)) {
|
||||
@@ -179,7 +179,7 @@ class LocalOrphanScanAdapterTest {
|
||||
}
|
||||
return referenced.contains(key.value()) || claimedKeys.contains(key.value());
|
||||
};
|
||||
return new LocalOrphanScanAdapter(
|
||||
return new LocalOrphanScan(
|
||||
ledger,
|
||||
LocalContentStoreFixture.properties(root, PublishMode.ATOMIC_MOVE_PREFERRED),
|
||||
GRACE,
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package dev.caskeleton.adapter.outbound.fileserver.platform.local;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowableOfType;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.filesystem.SecureDirectoryWalk;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode;
|
||||
import dev.caskeleton.application.fileserver.api.error.FileserverException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* A path the descriptor walk refuses is a permanent rejection wherever the refusal surfaces.
|
||||
*
|
||||
* <p>The publish move and the directory fsync call the walk directly rather than through the file
|
||||
* channel factory, and their failures went through the generic classifier, which reads the refusal
|
||||
* as an unavailable volume: a retryable 503 that a client would retry into a link that now points
|
||||
* somewhere else.
|
||||
*/
|
||||
class LocalStorageFailuresTest {
|
||||
|
||||
@TempDir Path root;
|
||||
|
||||
@Test
|
||||
@DisplayName("게시 이동 중 심볼릭 링크 경로 거부는 재시도 불가 PATH_OUTSIDE_NAMESPACE로 번역된다")
|
||||
void aSymbolicComponentRefusedByTheWalkIsAPermanentPathRejection() throws IOException {
|
||||
// given
|
||||
Assumptions.assumeTrue(SecureDirectoryWalk.isSupported(root));
|
||||
Path source = root.resolve("staging/aa/source.part");
|
||||
Path outside = root.resolve("outside");
|
||||
Files.createDirectories(source.getParent());
|
||||
Files.createDirectories(root.resolve("content"));
|
||||
Files.createDirectories(outside);
|
||||
Files.writeString(source, "payload");
|
||||
Files.createSymbolicLink(root.resolve("content/redirect"), outside);
|
||||
IOException refusal =
|
||||
catchThrowableOfType(
|
||||
IOException.class,
|
||||
() -> SecureDirectoryWalk.move(root, source, root.resolve("content/redirect/object")));
|
||||
|
||||
// when
|
||||
FileserverException translated = LocalStorageFailures.translate(refusal);
|
||||
|
||||
// then
|
||||
assertThat(List.of(translated.code(), translated.context().retryable()))
|
||||
.containsExactly(FileserverErrorCode.PATH_OUTSIDE_NAMESPACE, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("루트 밖을 가리키는 대상은 재시도 불가 PATH_OUTSIDE_NAMESPACE로 번역된다")
|
||||
void aTargetOutsideTheRootIsAPermanentPathRejection() {
|
||||
// given
|
||||
Assumptions.assumeTrue(SecureDirectoryWalk.isSupported(root));
|
||||
IOException refusal =
|
||||
catchThrowableOfType(
|
||||
IOException.class,
|
||||
() ->
|
||||
SecureDirectoryWalk.inParentOf(
|
||||
root, root.resolve("../elsewhere/object"), (directory, leaf) -> null));
|
||||
|
||||
// when
|
||||
FileserverException translated = LocalStorageFailures.translate(refusal);
|
||||
|
||||
// then
|
||||
assertThat(List.of(translated.code(), translated.context().retryable()))
|
||||
.containsExactly(FileserverErrorCode.PATH_OUTSIDE_NAMESPACE, false);
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -45,23 +45,23 @@ class LocalStorageGatewayContractTest {
|
||||
@TempDir Path root;
|
||||
|
||||
private LocalBlockingContentStore store;
|
||||
private LocalUploadStorageGateway uploads;
|
||||
private LocalCleanupContentGateway cleanup;
|
||||
private LocalCopyContentGateway copies;
|
||||
private LocalUploadStorage uploads;
|
||||
private LocalCleanupContent cleanup;
|
||||
private LocalCopyContent copies;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
store = LocalContentStoreFixture.store(root, PublishMode.ATOMIC_MOVE_PREFERRED);
|
||||
uploads = new LocalUploadStorageGateway(store);
|
||||
uploads = new LocalUploadStorage(store);
|
||||
cleanup =
|
||||
new LocalCleanupContentGateway(
|
||||
new LocalCleanupContent(
|
||||
store,
|
||||
new LocalOrphanScanAdapter(
|
||||
new LocalOrphanScan(
|
||||
key -> false,
|
||||
LocalContentStoreFixture.properties(root, PublishMode.ATOMIC_MOVE_PREFERRED),
|
||||
Duration.ZERO,
|
||||
Clock.systemUTC()));
|
||||
copies = new LocalCopyContentGateway(store, LocalContentStoreFixture.MAX_FILE);
|
||||
copies = new LocalCopyContent(store, LocalContentStoreFixture.MAX_FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
-1
@@ -4,7 +4,6 @@ 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.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.api.security.SanitizedFilename;
|
||||
import dev.caskeleton.application.fileserver.api.security.VerificationRequest;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
plugins {
|
||||
id 'ca.spring-library'
|
||||
id 'java-test-fixtures'
|
||||
id 'ca.auxiliary-source-set'
|
||||
id 'ca.platform-module'
|
||||
id 'me.champeau.jmh'
|
||||
}
|
||||
@@ -82,10 +81,27 @@ dependencies {
|
||||
// Performance certification and JMH benchmarks are separate source sets for their own reason: they
|
||||
// are slow, they assert on resource bounds rather than behaviour, and they must never be part of
|
||||
// the default unit lane.
|
||||
auxiliarySourceSets {
|
||||
// The testkit compiles against exactly what a test does: `implementation` inheritance runs
|
||||
sourceSet('integrationTest') { compilesAgainst 'main', 'testFixtures' }
|
||||
sourceSet('httpClientPerformanceTest') { compilesAgainst 'main', 'testFixtures' }
|
||||
testing {
|
||||
suites {
|
||||
integrationTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
httpClientPerformanceTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
configurations {
|
||||
integrationTestImplementation.extendsFrom testImplementation
|
||||
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
httpClientPerformanceTestImplementation.extendsFrom testImplementation
|
||||
httpClientPerformanceTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
+21
@@ -103,6 +103,27 @@ public final class ProviderRuntime {
|
||||
return health.get().reason();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases what the adapter holds, when it holds anything.
|
||||
*
|
||||
* <p>An SDK-backed adapter owns a client with a connection pool. The runtime is the only thing
|
||||
* that keeps the adapter, so it is also what lets it go: nothing else could reach the client to
|
||||
* close it once the process begins shutting down.
|
||||
*
|
||||
* @throws IllegalStateException if the adapter fails to release its resource
|
||||
*/
|
||||
public void release() {
|
||||
if (adapter instanceof AutoCloseable closeable) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(
|
||||
"provider adapter for profile " + profile.profileId().value() + " failed to close",
|
||||
failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Attempts currently in flight on this generation. */
|
||||
public int activeAttempts() {
|
||||
return limiter.activeAttempts();
|
||||
|
||||
+29
-1
@@ -11,7 +11,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/** Holds the current generation of every provider profile plus the generations still draining. */
|
||||
public final class ProviderRuntimeRegistry {
|
||||
public final class ProviderRuntimeRegistry implements AutoCloseable {
|
||||
|
||||
private final Map<ProviderProfileId, ProviderRuntime> current = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -137,4 +137,32 @@ public final class ProviderRuntimeRegistry {
|
||||
generations.removeIf(runtime -> runtime.activeAttempts() == 0);
|
||||
return generations.isEmpty() ? null : List.copyOf(generations);
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every generation's adapter at shutdown: the current ones and those still draining.
|
||||
*
|
||||
* <p>Each profile's adapter was built once at startup and never released, so an SDK client and
|
||||
* its connection pool outlived the context that created it. Every generation is attempted even
|
||||
* when one fails, and the first failure is reported with the rest attached.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
List<ProviderRuntime> generations = new ArrayList<>(current.values());
|
||||
draining.values().forEach(generations::addAll);
|
||||
IllegalStateException failure = null;
|
||||
for (ProviderRuntime generation : generations) {
|
||||
try {
|
||||
generation.release();
|
||||
} catch (IllegalStateException released) {
|
||||
if (failure == null) {
|
||||
failure = released;
|
||||
} else {
|
||||
failure.addSuppressed(released);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-1
@@ -40,7 +40,8 @@ import software.amazon.awssdk.services.sesv2.model.SendEmailResponse;
|
||||
* retries turned off, because a resend after a lost response is exactly the decision the evidence
|
||||
* model must make.
|
||||
*/
|
||||
public final class SesNotificationProviderAdapter implements NotificationProviderAdapter {
|
||||
public final class SesNotificationProviderAdapter
|
||||
implements NotificationProviderAdapter, AutoCloseable {
|
||||
|
||||
private static final ProviderId PROVIDER_ID = new ProviderId("ses");
|
||||
|
||||
@@ -69,6 +70,12 @@ public final class SesNotificationProviderAdapter implements NotificationProvide
|
||||
this.accessKeyId = Objects.requireNonNull(accessKeyId, "accessKeyId");
|
||||
}
|
||||
|
||||
/** Closes the SDK client and its connection pool; the runtime that owns this adapter calls it. */
|
||||
@Override
|
||||
public void close() {
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProviderId providerId() {
|
||||
return PROVIDER_ID;
|
||||
|
||||
+39
-2
@@ -17,10 +17,12 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProviderRuntimeRegistryTest {
|
||||
@@ -82,7 +84,31 @@ class ProviderRuntimeRegistryTest {
|
||||
runtime.acquireAttempt().close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("레지스트리를 닫으면 현재 세대와 drain 중인 세대의 어댑터 자원을 모두 닫는다")
|
||||
void closingTheRegistryClosesTheAdapterOfEveryRegisteredGeneration() {
|
||||
// given
|
||||
var registry = new ProviderRuntimeRegistry();
|
||||
var firstAdapter = new ClosingAdapter();
|
||||
var secondAdapter = new ClosingAdapter();
|
||||
var first = runtime(1, firstAdapter);
|
||||
registry.register(first);
|
||||
var inFlight = first.acquireAttempt();
|
||||
registry.replace(runtime(2, secondAdapter));
|
||||
|
||||
// when
|
||||
registry.close();
|
||||
|
||||
// then
|
||||
assertThat(List.of(firstAdapter.closed, secondAdapter.closed)).containsExactly(true, true);
|
||||
inFlight.close();
|
||||
}
|
||||
|
||||
private static ProviderRuntime runtime(long generation) {
|
||||
return runtime(generation, new StubAdapter());
|
||||
}
|
||||
|
||||
private static ProviderRuntime runtime(long generation, NotificationProviderAdapter adapter) {
|
||||
return new ProviderRuntime(
|
||||
new ProviderProfileSnapshot(
|
||||
PROFILE,
|
||||
@@ -103,12 +129,23 @@ class ProviderRuntimeRegistryTest {
|
||||
4096L,
|
||||
Duration.ofHours(1)),
|
||||
Map.of("topic", "com.example.app")),
|
||||
new StubAdapter(),
|
||||
adapter,
|
||||
new ProviderAttemptLimiter(1, 100, CLOCK));
|
||||
}
|
||||
|
||||
/** Adapter holding a resource, as an SDK-client-backed provider does. */
|
||||
private static final class ClosingAdapter extends StubAdapter implements AutoCloseable {
|
||||
|
||||
private boolean closed;
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Adapter that is never actually invoked by these runtime tests. */
|
||||
private static final class StubAdapter implements NotificationProviderAdapter {
|
||||
private static class StubAdapter implements NotificationProviderAdapter {
|
||||
|
||||
@Override
|
||||
public ProviderId providerId() {
|
||||
|
||||
+46
@@ -47,6 +47,7 @@ import java.util.Properties;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.sesv2.SesV2Client;
|
||||
|
||||
class SesNotificationProviderAdapterTest extends ProviderAdapterContract {
|
||||
|
||||
@@ -284,6 +285,51 @@ class SesNotificationProviderAdapterTest extends ProviderAdapterContract {
|
||||
assertThat(harness.received()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingTheAdapterClosesItsSdkClient() {
|
||||
// given
|
||||
var properties =
|
||||
new SesProviderProperties(
|
||||
harness.baseUri(),
|
||||
"ap-northeast-2",
|
||||
"transactional@example.com",
|
||||
Optional.empty(),
|
||||
Duration.ofSeconds(3));
|
||||
var client = new CloseRecordingSesClient();
|
||||
var adapter =
|
||||
new SesNotificationProviderAdapter(
|
||||
client,
|
||||
new SesRequestMapper(
|
||||
properties, new SmtpMimeMessageFactory(Session.getInstance(new Properties()))),
|
||||
new AttachmentIntegrityGuard(new UnconfiguredAttachmentResolver()),
|
||||
new SesFailureClassifier(),
|
||||
protector,
|
||||
SecurityFixtures.credentials("ses-primary"),
|
||||
"AKIAEXAMPLE");
|
||||
|
||||
// when
|
||||
adapter.close();
|
||||
|
||||
// then
|
||||
assertThat(client.closed).isTrue();
|
||||
}
|
||||
|
||||
/** An SDK client that does nothing but remember being closed. */
|
||||
private static final class CloseRecordingSesClient implements SesV2Client {
|
||||
|
||||
private boolean closed;
|
||||
|
||||
@Override
|
||||
public String serviceName() {
|
||||
return SERVICE_NAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private SesNotificationProviderAdapter adapter(
|
||||
ProviderCredentialManager credentials, AttachmentResolver attachments) {
|
||||
var properties =
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
plugins {
|
||||
id 'ca.spring-library'
|
||||
id 'ca.spring-config'
|
||||
id 'ca.auxiliary-source-set'
|
||||
}
|
||||
|
||||
// Driven adapter: provider-neutral semantic object-storage ports plus a bounded local-development
|
||||
@@ -22,9 +21,25 @@ description = 'Outbound adapter: object storage (S3/MinIO + local filesystem)'
|
||||
// MinIO/Testcontainers exercises are one physical INTEGRATION runtime. Contract/fault are
|
||||
// qualification meanings over that source set, not separate test kinds. The AWS sandbox keeps its
|
||||
// own source set because credentials/network authority make it a materially different environment.
|
||||
auxiliarySourceSets {
|
||||
sourceSet('integrationTest') { compilesAgainst 'main' }
|
||||
sourceSet('objectStorageAwsQualificationTest') { compilesAgainst 'main' }
|
||||
testing {
|
||||
suites {
|
||||
integrationTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
}
|
||||
}
|
||||
objectStorageAwsQualificationTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
configurations {
|
||||
integrationTestImplementation.extendsFrom testImplementation
|
||||
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
objectStorageAwsQualificationTestImplementation.extendsFrom testImplementation
|
||||
objectStorageAwsQualificationTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
}
|
||||
|
||||
dependencyManagement {
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileTransitionRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaFileRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaUploadSessionRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.UploadLeaseRepository;
|
||||
import java.time.Clock;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The file records and upload sessions, and the two read-side views over them.
|
||||
*
|
||||
* <p>Plain {@code @Bean} methods, like every other capability's persistence. These classes used to
|
||||
* be {@code @Repository} stereotypes, each repeating the capability condition, reached by a
|
||||
* component scan this leaf ran over its own package — a third way of assembling a module beside the
|
||||
* JPA leaf's scan and the notification leaf's explicit beans. The condition now lives once, on
|
||||
* {@link FileserverJpaPersistenceConfig}, which imports this.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverJpaMetadataStoreConfig {
|
||||
|
||||
@Bean
|
||||
JpaFileMetadata fileserverFileMetadata(
|
||||
JpaFileRepository files, FileTransitionRepository transitions, Clock clock) {
|
||||
return new JpaFileMetadata(files, transitions, clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaUploadSession fileserverUploadSessions(
|
||||
JpaUploadSessionRepository sessions, UploadLeaseRepository leases, Clock clock) {
|
||||
return new JpaUploadSession(sessions, leases, clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaStagingUploadLocator fileserverStagingUploadLocator(JpaUploadSessionRepository sessions) {
|
||||
return new JpaStagingUploadLocator(sessions);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaContentReferenceLedger fileserverContentReferenceLedger(JpaFileRepository files) {
|
||||
return new JpaContentReferenceLedger(files);
|
||||
}
|
||||
}
|
||||
+7
-8
@@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.persistence.autoconfigure.EntityScan;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
|
||||
/**
|
||||
@@ -31,12 +31,11 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
* the persistence unit, and a contribution that arrives after the {@code EntityManagerFactory} is
|
||||
* built arrives too late to be in it.
|
||||
*
|
||||
* <p>{@code @ComponentScan} is here for the reason the JPA leaf's {@code
|
||||
* JpaAdapterComponentsConfig} exists: the nine {@code @Repository} adapters in this package carry
|
||||
* the condition quoted above but were reached by no scan at all once the composition root stopped
|
||||
* scanning the persistence tree, so the condition had nothing to decide about.
|
||||
* {@code @EnableJpaRepositories} does not cover them — it registers Spring Data interfaces, and
|
||||
* these are classes that consume those interfaces.
|
||||
* <p>The stores are {@code @Bean}s of the two configurations imported here, under this one
|
||||
* condition. They used to be {@code @Repository} stereotypes, each repeating the condition, reached
|
||||
* by an {@code @ComponentScan} of this package — the module was assembled differently from its
|
||||
* neighbours and the condition was stated nine times. {@code @EnableJpaRepositories} still covers
|
||||
* the Spring Data interfaces, which is what it is for.
|
||||
*/
|
||||
@AutoConfiguration(
|
||||
beforeName =
|
||||
@@ -48,5 +47,5 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
matchIfMissing = true)
|
||||
@EntityScan(basePackages = "dev.caskeleton.adapter.outbound.persistence.fileserver")
|
||||
@EnableJpaRepositories(basePackages = "dev.caskeleton.adapter.outbound.persistence.fileserver")
|
||||
@ComponentScan(basePackages = "dev.caskeleton.adapter.outbound.persistence.fileserver")
|
||||
@Import({FileserverJpaMetadataStoreConfig.class, FileserverJpaQueueStoreConfig.class})
|
||||
public class FileserverJpaPersistenceConfig {}
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverCleanupRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverQuotaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.FileserverRecoveryRepository;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort;
|
||||
import java.time.Clock;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Quota reservations and the two work queues — cleanup and recovery.
|
||||
*
|
||||
* <p>Imported by {@link FileserverJpaPersistenceConfig}, which carries the capability condition;
|
||||
* see {@link FileserverJpaMetadataStoreConfig} for why these are beans rather than scanned
|
||||
* stereotypes.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverJpaQueueStoreConfig {
|
||||
|
||||
@Bean
|
||||
JpaFileQuota fileserverFileQuota(FileserverQuotaRepository reservations, Clock clock) {
|
||||
return new JpaFileQuota(reservations, clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaQuotaCommit fileserverQuotaCommit(
|
||||
FileserverQuotaRepository reservations, FileMetadataPort metadataStore, Clock clock) {
|
||||
return new JpaQuotaCommit(reservations, metadataStore, clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaQuotaReclaim fileserverQuotaReclaim(FileserverQuotaRepository reservations, Clock clock) {
|
||||
return new JpaQuotaReclaim(reservations, clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaCleanupQueue fileserverCleanupQueue(FileserverCleanupRepository items, Clock clock) {
|
||||
return new JpaCleanupQueue(items, clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaRecoveryQueue fileserverRecoveryQueue(FileserverRecoveryRepository items, Clock clock) {
|
||||
return new JpaRecoveryQueue(items, clock);
|
||||
}
|
||||
}
|
||||
-8
@@ -15,9 +15,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Durable, at-most-one-worker cleanup queue over {@code fs_cleanup_item}.
|
||||
@@ -32,12 +30,6 @@ import org.springframework.stereotype.Repository;
|
||||
* <p>Staging cleanups carry an upload id and published cleanups carry a content key. The row keeps
|
||||
* both columns nullable for that reason; which one is set is what tells the worker where to look.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaCleanupQueue implements CleanupQueuePort {
|
||||
|
||||
/** After this many failed attempts an item stops being rescheduled. */
|
||||
|
||||
-8
@@ -3,8 +3,6 @@ package dev.caskeleton.adapter.outbound.persistence.fileserver;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.repository.JpaFileRepository;
|
||||
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedgerPort;
|
||||
import dev.caskeleton.application.fileserver.api.ContentKey;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Answers the orphan scan's one question against {@code fs_file}.
|
||||
@@ -14,12 +12,6 @@ import org.springframework.stereotype.Repository;
|
||||
* cleanup worker's precondition check, and a DELETED row still proves the key is not free to be
|
||||
* reclaimed by a second, unrelated deletion path.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaContentReferenceLedger implements ContentReferenceLedgerPort {
|
||||
|
||||
private final JpaFileRepository files;
|
||||
|
||||
+2
-10
@@ -21,9 +21,7 @@ import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* JPA-backed {@link FileMetadataPort}.
|
||||
@@ -38,13 +36,7 @@ import org.springframework.stereotype.Repository;
|
||||
* answer — the modifying statement refuses to run outside a transaction, which is the failure mode
|
||||
* worth having.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaFileMetadataStore implements FileMetadataPort {
|
||||
public class JpaFileMetadata implements FileMetadataPort {
|
||||
|
||||
private final JpaFileRepository files;
|
||||
private final FileTransitionRepository transitions;
|
||||
@@ -53,7 +45,7 @@ public class JpaFileMetadataStore implements FileMetadataPort {
|
||||
/** The states the transition table lets into DELETING, read from the table itself. */
|
||||
private final List<String> deletableStates;
|
||||
|
||||
public JpaFileMetadataStore(
|
||||
public JpaFileMetadata(
|
||||
JpaFileRepository files, FileTransitionRepository transitions, Clock clock) {
|
||||
this.files = files;
|
||||
this.transitions = transitions;
|
||||
+2
-10
@@ -13,8 +13,6 @@ import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* JPA-backed {@link FileQuotaPort}.
|
||||
@@ -22,18 +20,12 @@ import org.springframework.stereotype.Repository;
|
||||
* <p>Reservation, extension, commit, and release are conditional statements, so a reservation that
|
||||
* already expired or was released can never be extended or committed.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaFileQuotaService implements FileQuotaPort {
|
||||
public class JpaFileQuota implements FileQuotaPort {
|
||||
|
||||
private final FileserverQuotaRepository reservations;
|
||||
private final Clock clock;
|
||||
|
||||
public JpaFileQuotaService(FileserverQuotaRepository reservations, Clock clock) {
|
||||
public JpaFileQuota(FileserverQuotaRepository reservations, Clock clock) {
|
||||
this.reservations = reservations;
|
||||
this.clock = clock;
|
||||
}
|
||||
+2
-10
@@ -12,9 +12,7 @@ import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Settles an upload's share of its scope's quota ledger.
|
||||
@@ -34,13 +32,7 @@ import org.springframework.stereotype.Repository;
|
||||
* recorded. Durable usage that goes unrecorded because a reservation expired is how a quota ledger
|
||||
* silently drifts below the truth.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaQuotaCommitGateway implements QuotaCommitPort {
|
||||
public class JpaQuotaCommit implements QuotaCommitPort {
|
||||
|
||||
private static final Limit OLDEST = Limit.of(1);
|
||||
|
||||
@@ -48,7 +40,7 @@ public class JpaQuotaCommitGateway implements QuotaCommitPort {
|
||||
private final FileMetadataPort metadataStore;
|
||||
private final Clock clock;
|
||||
|
||||
public JpaQuotaCommitGateway(
|
||||
public JpaQuotaCommit(
|
||||
FileserverQuotaRepository reservations, FileMetadataPort metadataStore, Clock clock) {
|
||||
this.reservations = reservations;
|
||||
this.metadataStore = metadataStore;
|
||||
+2
-10
@@ -6,9 +6,7 @@ import dev.caskeleton.application.fileserver.api.metadata.QuotaScope;
|
||||
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimPort;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Returns reclaimed bytes to a scope's committed total.
|
||||
@@ -26,20 +24,14 @@ import org.springframework.stereotype.Repository;
|
||||
* a scope cannot owe negative bytes, and a reclaim that outruns the recorded total means the total
|
||||
* was already understated, which a negative balance would not fix.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaQuotaReclaimGateway implements QuotaReclaimPort {
|
||||
public class JpaQuotaReclaim implements QuotaReclaimPort {
|
||||
|
||||
private static final Limit RECLAIM_PAGE = Limit.of(64);
|
||||
|
||||
private final FileserverQuotaRepository reservations;
|
||||
private final Clock clock;
|
||||
|
||||
public JpaQuotaReclaimGateway(FileserverQuotaRepository reservations, Clock clock) {
|
||||
public JpaQuotaReclaim(FileserverQuotaRepository reservations, Clock clock) {
|
||||
this.reservations = reservations;
|
||||
this.clock = clock;
|
||||
}
|
||||
-8
@@ -9,9 +9,7 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Durable recovery queue over {@code fs_recovery_item}.
|
||||
@@ -25,12 +23,6 @@ import org.springframework.stereotype.Repository;
|
||||
* QUARANTINE_REQUIRED} are the two answers a human has to act on, and both are worthless if the
|
||||
* record of what the system concluded disappears with the item.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaRecoveryQueue implements RecoveryQueuePort {
|
||||
|
||||
private static final String STATUS_PENDING = "PENDING";
|
||||
|
||||
-8
@@ -7,9 +7,7 @@ import dev.caskeleton.application.fileserver.api.UploadId;
|
||||
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Maps a file back to the upload that last staged it.
|
||||
@@ -18,12 +16,6 @@ import org.springframework.stereotype.Repository;
|
||||
* one session row, and an older one names a staging object that has since been reclaimed — treating
|
||||
* that as live evidence would tell reconciliation the upload is resumable when it is not.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaStagingUploadLocator implements StagingUploadLocatorPort {
|
||||
|
||||
private static final Limit NEWEST = Limit.of(1);
|
||||
|
||||
+2
-10
@@ -17,9 +17,7 @@ import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.data.domain.Limit;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* JPA-backed {@link UploadSessionPort} with database writer leases.
|
||||
@@ -32,19 +30,13 @@ import org.springframework.stereotype.Repository;
|
||||
* says nothing about whether the upload is still one anybody may write to, so cleanup could delete
|
||||
* the staged bytes of an upload a writer was about to take a lease on.
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = "enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class JpaUploadSessionStore implements UploadSessionPort {
|
||||
public class JpaUploadSession implements UploadSessionPort {
|
||||
|
||||
private final JpaUploadSessionRepository sessions;
|
||||
private final UploadLeaseRepository leases;
|
||||
private final Clock clock;
|
||||
|
||||
public JpaUploadSessionStore(
|
||||
public JpaUploadSession(
|
||||
JpaUploadSessionRepository sessions, UploadLeaseRepository leases, Clock clock) {
|
||||
this.sessions = sessions;
|
||||
this.leases = leases;
|
||||
@@ -30,7 +30,7 @@ packages.
|
||||
|---|---|
|
||||
| `autoconfigure` | package-private Boot composition root/runtime: vendor and optional-store imports and provider runtime beans. It is intentionally not exported as public API |
|
||||
| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | framework-free contracts: operation and query names, the stable error hierarchy, commit-completion evidence, keyset cursors |
|
||||
| `transaction` | `SpringTransactionPort`, the one transaction engine (`TransactionPort` over Spring's `PlatformTransactionManager`) |
|
||||
| `transaction` | `SpringTransaction`, the one transaction engine (`TransactionPort` over Spring's `PlatformTransactionManager`) |
|
||||
| `springdata` | repository fragments, safe sort, fetch plans, keyset execution, stream guard |
|
||||
| `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, statistics, batch, bulk DML, stateless session |
|
||||
| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE classification, lock options, JSONB, arrays and ranges, COPY |
|
||||
@@ -55,7 +55,7 @@ Because Boot loads those candidates independently, **both** require
|
||||
`ca-skeleton.persistence-jpa.enabled=true`. The first owns vendor/entity/repository and
|
||||
capability-store imports. The second contributes only the provider runtime beans
|
||||
(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`). The
|
||||
transaction engine is `SpringTransactionPort` alone; the second engine
|
||||
transaction engine is `SpringTransaction` alone; the second engine
|
||||
(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`) was removed on 2026-09-25 — see
|
||||
`docs/capability-status.md`. Never rely on the first candidate's condition to gate the sibling
|
||||
import candidate.
|
||||
@@ -89,7 +89,7 @@ not grow by wiring accident.
|
||||
|
||||
- No `GenericRepository<T, ID>` and no platform base repository. Domains own their repositories.
|
||||
- `TransactionCompletionUnknownException` is never retried. `JpaFailureContext` refuses to
|
||||
represent a retryable completion-unknown failure, and `SpringTransactionPort` retries nothing.
|
||||
represent a retryable completion-unknown failure, and `SpringTransaction` retries nothing.
|
||||
- A caller that retries re-runs the whole use case in a new transaction and a new Persistence
|
||||
Context.
|
||||
- OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates.
|
||||
@@ -126,7 +126,7 @@ nobody tested.
|
||||
- Spring Data repositories.
|
||||
- Persistence mappers.
|
||||
- Repository adapter implementations.
|
||||
- Outbox append: one model. `OutboxStoreAdapter` implements `OutboxAppendPort` and persists a
|
||||
- Outbox append: one model. `JpaOutboxStore` implements `OutboxAppendPort` and persists a
|
||||
`ValidatedIntegrationEvent`'s exact envelope bytes and hashes; a claim restores the same event
|
||||
from them. A row without complete canonical metadata is unreadable and goes to DEAD, never
|
||||
published by guess. `V19` refuses unpublished pre-canonical rows.
|
||||
@@ -135,10 +135,10 @@ nobody tested.
|
||||
conditional UPDATE on `event_id` + `IN_FLIGHT` + owner + token and return `APPLIED`/`STALE`. A
|
||||
completion never loads and overwrites a row. The V2 outbox generation was deleted on 2026-09-25
|
||||
(`docs/capability-status.md`).
|
||||
- `TransactionPort` implementation (`SpringTransactionPort`) — the bridge between
|
||||
- `TransactionPort` implementation (`SpringTransaction`) — the bridge between
|
||||
application transactional intent and Spring's `PlatformTransactionManager`.
|
||||
- Audit-metadata base + actor seam (`audit/AuditableEntity`, `audit/AuditContextPort`,
|
||||
`audit/DomainContextAuditContextPort`) — see "Persistence auditing contract" below.
|
||||
`audit/DomainContextAuditContext`) — see "Persistence auditing contract" below.
|
||||
- Vendor SPI extension points shared by all RDBMS vendors:
|
||||
- `outbox/jpa/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED); the implementations sit beside it in `outbox/postgresql` and `outbox/h2`.
|
||||
- `failure/SqlStateErrorMapping` — vendor module contributes vendor-specific SQLState rows.
|
||||
@@ -216,7 +216,7 @@ should not exist.
|
||||
|
||||
## TransactionPort implementation contract
|
||||
|
||||
`SpringTransactionPort` pre-builds one `TransactionTemplate` per mode:
|
||||
`SpringTransaction` pre-builds one `TransactionTemplate` per mode:
|
||||
|
||||
| Mode | Propagation | Isolation | Read-only |
|
||||
|---|---|---|---|
|
||||
|
||||
@@ -24,8 +24,8 @@ bean과 함께 Boot의 JDBC·Hibernate·Spring Data JPA·Flyway 자동 설정도
|
||||
추가되므로 DataSource·풀·EntityManagerFactory·Flyway가 만들어지지 않고 DB 없이 기동한다. 그래서 DB가
|
||||
필요한 다른 capability(notification·fileserver 저장소, messaging JDBC outbox/inbox 등)와 함께 끌 수는 없다)
|
||||
|
||||
- 포트 구현: `TransactionPort`(`SpringTransactionPort`), `DistributedLockPort`(단일 인스턴스는
|
||||
in-process, `APP_MULTI_INSTANCE_ENABLED=true`면 JDBC `INT_LOCK` + `MeteredDistributedLockPort`
|
||||
- 포트 구현: `TransactionPort`(`SpringTransaction`), `DistributedLockPort`(단일 인스턴스는
|
||||
in-process, `APP_MULTI_INSTANCE_ENABLED=true`면 JDBC `INT_LOCK` + `MeteredDistributedLock`
|
||||
데코레이터 = `distributedLockProvider`), outbox store(`OutboxStorePort`, `APP_OUTBOX_ENABLED=true`),
|
||||
PostgreSQL 멱등성 store(`APP_IDEMPOTENCY_PROVIDER=postgresql`), audit·operation·live-event store.
|
||||
- 엔티티/리포지토리 스캔, vendor 조립(PostgreSQL 기본, H2는 개발용), Flyway 위치.
|
||||
@@ -101,7 +101,7 @@ metric은 기본으로 하나도 나오지 않는다. `jpa.query.*`는 서비스
|
||||
promotion gate, 생성하는 곳 없는 `JpaTransactionObservation` 등)은 `docs/capability-status.md`
|
||||
"제거된 코드"에 있다.
|
||||
|
||||
## transaction — `SpringTransactionPort`
|
||||
## transaction — `SpringTransaction`
|
||||
|
||||
### 왜 모드별 템플릿을 미리 만들어 두나
|
||||
`TransactionTemplate` 은 문서상 thread-safe 지만 **mutable** 하다. 매 호출마다 propagation /
|
||||
@@ -123,7 +123,7 @@ write template을 재사용한다. 차이는 실행 전 precondition이다.
|
||||
예외로 전파된다. 이 보장은 action이 외부 객체를 직접 변경하는 것을 되돌리는 보상이 아니라,
|
||||
경계의 반환값을 성공으로 노출하지 않는 계약이다.
|
||||
|
||||
## audit — `AuditableEntity` / `AuditContextPort` / `DomainContextAuditContextPort`
|
||||
## audit — `AuditableEntity` / `AuditContextPort` / `DomainContextAuditContext`
|
||||
|
||||
### 캡처 메커니즘 — Manual explicit-set (D1 현재 스켈레톤 기본값)
|
||||
`AuditableEntity` 의 네 필드(`created_at` / `updated_at` / `created_by` / `updated_by`)는 평범한
|
||||
@@ -156,7 +156,7 @@ actor 의 **값 의미론**(user id vs email vs subject claim)은 application/we
|
||||
포트가 보장하는 건 오직 "non-null actor"(프레임워크의 blank-on-absent 가 아니라) 하나 —
|
||||
principal 이 없으면 `"system"`.
|
||||
|
||||
`DomainContextAuditContextPort` 는 actor id 를 runtime-context-propagation seam
|
||||
`DomainContextAuditContext` 는 actor id 를 runtime-context-propagation seam
|
||||
(`DomainContextPropagator`)에서 읽는다. 그 브랜치가 canonical actor key 를 소유하지만 API 가
|
||||
확정되기 전까지 이 어댑터가 `ACTOR_KEY` 뒤로 격리해, 키가 바뀌어도 정확히 한 클래스만 손대게
|
||||
한다(D5 Open Risk). 빈/blank context 값은 null/blank actor 가 아니라 `"system"` 으로 떨어뜨려
|
||||
@@ -205,7 +205,7 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만
|
||||
|
||||
`ca-skeleton.capabilities.idempotency.provider=postgresql` 일 때만 켜진다
|
||||
(`autoconfigure/PostgreSqlIdempotencyStoreConfig`). 이 leaf 는 `IdempotencyStorePort` 구현
|
||||
(`PostgreSqlOwnerSafeIdempotencyStore`) 하나만 내놓고, executor 는 app-bootstrap
|
||||
(`PostgreSqlIdempotencyStore`) 하나만 내놓고, executor 는 app-bootstrap
|
||||
`IdempotencyProviderSelectionConfig` 가 만든다. V1 JDBC store 와 `jdbc` provider 값은 없다.
|
||||
|
||||
- **스키마**: 기본 테이블은 primary Flyway(`db/migration/postgresql/V1__idempotency_record.sql`)가,
|
||||
@@ -221,11 +221,11 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만
|
||||
(`IdempotencyRecordJpaRepository` 사용, 기본 10분 간격 `reaper-interval`)가 지난 행을 지운다.
|
||||
reaper 는 provider 가 `postgresql` 일 때만 돈다.
|
||||
|
||||
## outbox — `OutboxStoreAdapter` 외
|
||||
## outbox — `JpaOutboxStore` 외
|
||||
|
||||
스키마는 Flyway(`V3__outbox_event.sql`)가 소유하고, `V13__outbox_canonical_transport_compatibility.sql`이
|
||||
canonical metadata와 exact `BYTEA envelope_bytes`를 더했다. append 모델은 canonical 하나다(2026-09-28,
|
||||
소유자 결정 7): `OutboxStoreAdapter`가 `OutboxAppendPort`(`ValidatedIntegrationEvent`)와
|
||||
소유자 결정 7): `JpaOutboxStore`가 `OutboxAppendPort`(`ValidatedIntegrationEvent`)와
|
||||
`OutboxStorePort`를 함께 구현하고, `ca-skeleton.outbox.enabled=true`일 때만 존재한다. row는 validated
|
||||
event의 exact envelope bytes와 hash를 저장하고, claim은 그 bytes로 같은 event를 복원한다
|
||||
(`ClaimedOutboxEvent`). `event_type`·`aggregate_id`·`correlation_id`는 claim gate와 metrics query를
|
||||
@@ -323,7 +323,7 @@ A가 FAILED로 바꾸면 다시 발행되고(중복 전달), A의 늦은 PUBLISH
|
||||
2-요소 배열 리스트를 돌려준다(각각 outbox.pending.size, outbox.publisher.lag gauge 용).
|
||||
두 쿼리 모두 PUBLISHED row 는 세지 않는다 — retention 기간 동안 테이블 대부분이 PUBLISHED 라,
|
||||
매 poll 마다 테이블 전체를 세게 된다.
|
||||
`OutboxStoreAdapter.oldestUnpublishedAgeSecondsByEventType` 가 `HashMap` 을 쓰는 건 키가
|
||||
`JpaOutboxStore.oldestUnpublishedAgeSecondsByEventType` 가 `HashMap` 을 쓰는 건 키가
|
||||
enum 이 아니라 String(event-type 이름)이기 때문이다 — `countByStatus()` 는 키가
|
||||
`OutboxEventStatus` enum 이라 `EnumMap` 을 쓴다(두 반환 타입이 의도적으로 다름).
|
||||
|
||||
@@ -362,7 +362,7 @@ machine-readable SSOT다(개수는 registry가 소유한다). `selected` base ca
|
||||
|
||||
### owner-safe idempotency
|
||||
|
||||
`PostgreSqlOwnerSafeIdempotencyStore`는 row lock을 얻은 뒤 `clock_timestamp()`를 평가한다.
|
||||
`PostgreSqlIdempotencyStore`는 row lock을 얻은 뒤 `clock_timestamp()`를 평가한다.
|
||||
claim takeover와 start/renew/complete/fail/release는 scope/state/owner/attempt/claim operation/
|
||||
state revision을 SQL predicate로 다시 검증한다. expired `CLAIMED`만 takeover하며 expired
|
||||
`EXECUTING`은 `ABANDONED`로 닫고 reconciliation을 요구한다. raw client key는 저장하지 않고
|
||||
@@ -415,7 +415,7 @@ stream migration이 중단되면 history/registry/object 상태를 먼저 확인
|
||||
provider 선택표(flag → bean → registry)의 SSOT 는 CLAUDE.md(또는 app-bootstrap 와이어링)다.
|
||||
여기서는 어댑터/설정 결정 근거만 적는다.
|
||||
|
||||
### `LockRegistryDistributedLockAdapter` 계약
|
||||
### `LockRegistryDistributedLock` 계약
|
||||
- **D4 — transaction-commit ordering invariant.** 이 어댑터는 트랜잭션 경계를 관리하지 않는다.
|
||||
호출자는 보호된 트랜잭션이 **커밋된 뒤에만** 핸들(`DistributedLock.close()`)을 release 해야
|
||||
한다. 커밋 전(트랜잭션 안)에 release 하면 lost-update race 가 생긴다.
|
||||
@@ -447,7 +447,7 @@ provider 선택표(flag → bean → registry)의 SSOT 는 CLAUDE.md(또는 app-
|
||||
|
||||
### `DistributedLockPersistenceConfig` 와이어링 결정
|
||||
- `jdbcDistributedLock` 빈은 일부러 `@Primary` 가 아니다. 같은 설정이 이를 metrics
|
||||
데코레이터(`MeteredDistributedLockPort`, package-private)로 감싸 `@Primary`
|
||||
데코레이터(`MeteredDistributedLock`, package-private)로 감싸 `@Primary`
|
||||
`distributedLockProvider` 빈으로 노출한다. 예전에는 app-bootstrap의 `DistributedLockConfig`가
|
||||
감쌌지만, JDBC 락이 있을 때만 의미가 있는 코드라 이 모듈로 옮겼다. SI 타입은 여전히 이 모듈
|
||||
밖으로 보이지 않는다(SI 는 `implementation` 의존).
|
||||
@@ -468,7 +468,7 @@ provider 선택표(flag → bean → registry)의 SSOT 는 CLAUDE.md(또는 app-
|
||||
이어야 한다 — TTL 이 waitTime 보다 먼저 만료되면 첫 holder 의 보호작업이 끝나기 전에 두 번째
|
||||
holder 가 락을 잡을 수 있다.
|
||||
|
||||
### `MeteredDistributedLockPort` (app-bootstrap에서 이동)
|
||||
### `MeteredDistributedLock` (app-bootstrap에서 이동)
|
||||
- **`DistributedLockPort`를 감싸는 얇은 Micrometer 데코레이터다.** `tryAcquire` 호출마다
|
||||
`lock.acquisition` 카운터를 `outcome` 태그와 함께 1 증가시킨다. 태그 값은 세 가지: `acquired`(락
|
||||
획득 성공, 위임 핸들 반환), `timeout`(`LockAcquisitionTimeoutException` 발생), `error`(그 외 모든
|
||||
|
||||
@@ -2,7 +2,6 @@ plugins {
|
||||
id 'ca.spring-library'
|
||||
id 'ca.spring-config'
|
||||
id 'java-test-fixtures'
|
||||
id 'ca.auxiliary-source-set'
|
||||
id 'ca.api-surface'
|
||||
}
|
||||
|
||||
@@ -21,15 +20,31 @@ plugins {
|
||||
// The testkit is its own source set rather than part of `test` because more than one lane consumes
|
||||
// it and because a source set whose dependencies are declared only on the test configurations gives
|
||||
// the design's "no production module depends on the testkit" guarantee without a new Gradle project.
|
||||
auxiliarySourceSets {
|
||||
sourceSet('postgresqlIntegrationTest') {
|
||||
// 'testFixtures' as well as 'main': the integration lane consumed the testkit through the
|
||||
// convention's `consumedBy 'test', 'postgresqlIntegrationTest'`, and java-test-fixtures only
|
||||
// wires `test` on its own. The lane has to say so (ADR-BUILD-001).
|
||||
compilesAgainst 'main', 'testFixtures'
|
||||
inherits 'implementation', 'compileOnly', 'runtimeOnly', 'annotationProcessor'
|
||||
testing {
|
||||
suites {
|
||||
postgresqlIntegrationTest(JvmTestSuite) {
|
||||
// testFixtures as well as the project: java-test-fixtures wires only `test` on its own,
|
||||
// so the integration lane has to say so (ADR-BUILD-001).
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
jpaPlatformPerformanceTest(JvmTestSuite) {
|
||||
dependencies {
|
||||
implementation project()
|
||||
implementation testFixtures(project())
|
||||
}
|
||||
}
|
||||
}
|
||||
sourceSet('jpaPlatformPerformanceTest') { compilesAgainst 'main', 'testFixtures' }
|
||||
}
|
||||
configurations {
|
||||
postgresqlIntegrationTestImplementation.extendsFrom testImplementation
|
||||
postgresqlIntegrationTestCompileOnly.extendsFrom testCompileOnly
|
||||
postgresqlIntegrationTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
postgresqlIntegrationTestAnnotationProcessor.extendsFrom testAnnotationProcessor
|
||||
jpaPlatformPerformanceTestImplementation.extendsFrom testImplementation
|
||||
jpaPlatformPerformanceTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -249,9 +264,11 @@ tasks.named('test') {
|
||||
inputs.dir(new File(rootProject.projectDir.parentFile, '.github/workflows'))
|
||||
inputs.file(file('build.gradle'))
|
||||
inputs.dir(file('src/jpaPlatformPerformanceTest/java'))
|
||||
// AppliedMigrationImmutabilityTest pins the notification stream where it now lives.
|
||||
// AppliedMigrationImmutabilityTest pins the notification and fileserver streams where they live.
|
||||
inputs.dir(file('../persistence-notification/src/main/resources/db/migration'))
|
||||
.withPropertyName('notificationMigrations')
|
||||
inputs.dir(file('../persistence-fileserver/src/main/resources/db/migration'))
|
||||
.withPropertyName('fileserverMigrations')
|
||||
}
|
||||
|
||||
// verifyJpaApiSurface — every public type this leaf exposes is a committed decision.
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ import org.springframework.stereotype.Component;
|
||||
* isolated behind {@link #ACTOR_KEY} so a future key change touches one class (see README "audit").
|
||||
*/
|
||||
@Component
|
||||
public class DomainContextAuditContextPort implements AuditContextPort {
|
||||
public class DomainContextAuditContext implements AuditContextPort {
|
||||
|
||||
static final String SYSTEM_ACTOR = "system";
|
||||
|
||||
@@ -18,7 +18,7 @@ public class DomainContextAuditContextPort implements AuditContextPort {
|
||||
|
||||
private final DomainContextPropagator propagator;
|
||||
|
||||
public DomainContextAuditContextPort(DomainContextPropagator propagator) {
|
||||
public DomainContextAuditContext(DomainContextPropagator propagator) {
|
||||
this.propagator = propagator;
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream;
|
||||
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlIdempotencyStore;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
@@ -24,7 +24,7 @@ class PostgreSqlIdempotencyStoreConfig {
|
||||
|
||||
@Bean
|
||||
IdempotencyStorePort postgreSqlOwnerSafeIdempotencyStore(JdbcOperations jdbc) {
|
||||
return new PostgreSqlOwnerSafeIdempotencyStore(jdbc);
|
||||
return new PostgreSqlIdempotencyStore(jdbc);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+3
-3
@@ -14,9 +14,9 @@ import org.springframework.context.annotation.FilterType;
|
||||
* beans rather than assembling them and hoping each one remembered to carry the switch.
|
||||
*
|
||||
* <p>What was missing is the other half. Eight classes in this leaf are written as scanned
|
||||
* components — {@code SpringTransactionPort}, {@code PersistenceExceptionTranslator}, {@code
|
||||
* StandardSqlStateErrorMapping}, {@code DomainContextAuditContextPort}, the idempotency store and
|
||||
* its reaper, and the outbox store and its reaper — and once the broad scan stopped reaching them,
|
||||
* components — {@code SpringTransaction}, {@code PersistenceExceptionTranslator}, {@code
|
||||
* StandardSqlStateErrorMapping}, {@code DomainContextAuditContext}, the idempotency store and its
|
||||
* reaper, and the outbox store and its reaper — and once the broad scan stopped reaching them,
|
||||
* nothing else did. They are annotated {@code @Component} and {@code @Repository} and were beans in
|
||||
* no running application: {@code TransactionPort} in particular had no implementation at all, so
|
||||
* every use case that opens a transaction had no port to open it with.
|
||||
|
||||
+3
-3
@@ -55,7 +55,7 @@ import org.springframework.jdbc.core.JdbcOperations;
|
||||
* second store beside its own, which the composition root refuses. The persistence leaf builds it
|
||||
* for {@code provider=postgresql} and only while the JPA capability is enabled.
|
||||
*/
|
||||
public class PostgreSqlOwnerSafeIdempotencyStore implements IdempotencyStorePort {
|
||||
public class PostgreSqlIdempotencyStore implements IdempotencyStorePort {
|
||||
|
||||
static final int INLINE_RESPONSE_MAX_BYTES = 8 * 1024;
|
||||
|
||||
@@ -78,11 +78,11 @@ public class PostgreSqlOwnerSafeIdempotencyStore implements IdempotencyStorePort
|
||||
private final IdempotencyClaimGateway claims;
|
||||
private final IdempotencyTransitionGateway transitions;
|
||||
|
||||
public PostgreSqlOwnerSafeIdempotencyStore(JdbcOperations jdbc) {
|
||||
public PostgreSqlIdempotencyStore(JdbcOperations jdbc) {
|
||||
this(jdbc, new SecureRandom());
|
||||
}
|
||||
|
||||
PostgreSqlOwnerSafeIdempotencyStore(JdbcOperations jdbc, SecureRandom secureRandom) {
|
||||
PostgreSqlIdempotencyStore(JdbcOperations jdbc, SecureRandom secureRandom) {
|
||||
Objects.requireNonNull(jdbc, "jdbc");
|
||||
this.secureRandom = Objects.requireNonNull(secureRandom, "secureRandom");
|
||||
this.guard = new IdempotencyCapabilityGuard(jdbc, dataSourceOf(jdbc), ACTIVE_CAPABILITY_SQL);
|
||||
+2
-2
@@ -46,7 +46,7 @@ import org.springframework.stereotype.Repository;
|
||||
name = "vendor",
|
||||
havingValue = "postgresql",
|
||||
matchIfMissing = true)
|
||||
public class JpaLiveEventReplayAdapter implements LiveEventReplayPort {
|
||||
public class JpaLiveEventReplay implements LiveEventReplayPort {
|
||||
|
||||
/** The most one replay call will load, whatever the caller asks for. */
|
||||
public static final int MAX_REPLAY_LIMIT = 500;
|
||||
@@ -73,7 +73,7 @@ public class JpaLiveEventReplayAdapter implements LiveEventReplayPort {
|
||||
* @param clock the clock retention is measured against
|
||||
* @param retention how long an appended event stays replayable
|
||||
*/
|
||||
public JpaLiveEventReplayAdapter(
|
||||
public JpaLiveEventReplay(
|
||||
LiveEventJpaRepository repository,
|
||||
JdbcOperations jdbc,
|
||||
Clock clock,
|
||||
+5
-5
@@ -17,8 +17,8 @@ import org.springframework.integration.support.locks.DefaultLockRegistry;
|
||||
/**
|
||||
* Spring wiring for the distributed-lock infrastructure: in-process {@link DefaultLockRegistry} by
|
||||
* default, JDBC {@link JdbcLockRegistry} when {@code multi-instance-enabled=true}, wrapped in the
|
||||
* {@link MeteredDistributedLockPort} metrics decorator as the primary {@code
|
||||
* distributedLockProvider}. See README "lock" for the provider-selection and wiring rationale.
|
||||
* {@link MeteredDistributedLock} metrics decorator as the primary {@code distributedLockProvider}.
|
||||
* See README "lock" for the provider-selection and wiring rationale.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
// LockSettings is bound here rather than by the composition root's @ConfigurationPropertiesScan,
|
||||
@@ -36,7 +36,7 @@ public class DistributedLockPersistenceConfig {
|
||||
havingValue = "false",
|
||||
matchIfMissing = true)
|
||||
DistributedLockPort inProcessDistributedLock(LockSettings settings) {
|
||||
return new LockRegistryDistributedLockAdapter(new DefaultLockRegistry(), settings.leaseTtl());
|
||||
return new LockRegistryDistributedLock(new DefaultLockRegistry(), settings.leaseTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -72,7 +72,7 @@ public class DistributedLockPersistenceConfig {
|
||||
havingValue = "true")
|
||||
DistributedLockPort jdbcDistributedLock(
|
||||
JdbcLockRegistry jdbcLockRegistry, LockSettings settings) {
|
||||
return new LockRegistryDistributedLockAdapter(jdbcLockRegistry, settings.leaseTtl());
|
||||
return new LockRegistryDistributedLock(jdbcLockRegistry, settings.leaseTtl());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,6 +89,6 @@ public class DistributedLockPersistenceConfig {
|
||||
DistributedLockPort distributedLockProvider(
|
||||
@Qualifier("jdbcDistributedLock") DistributedLockPort jdbcDistributedLock,
|
||||
ObjectProvider<MeterRegistry> meterRegistry) {
|
||||
return new MeteredDistributedLockPort(jdbcDistributedLock, meterRegistry);
|
||||
return new MeteredDistributedLock(jdbcDistributedLock, meterRegistry);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -14,12 +14,12 @@ import org.springframework.integration.support.locks.LockRegistry;
|
||||
* manage the transaction boundary, uses a finite-wait try-lock, and leaves lease-expiry handling to
|
||||
* the metered decorator. See README "lock" for the D4/D5/TTL/SI-LOCK-C5 contracts.
|
||||
*/
|
||||
public class LockRegistryDistributedLockAdapter implements DistributedLockPort {
|
||||
public class LockRegistryDistributedLock implements DistributedLockPort {
|
||||
|
||||
private final LockRegistry<? extends Lock> registry;
|
||||
private final Duration configuredTtl;
|
||||
|
||||
public LockRegistryDistributedLockAdapter(
|
||||
public LockRegistryDistributedLock(
|
||||
LockRegistry<? extends Lock> registry, Duration configuredTtl) {
|
||||
this.registry = registry;
|
||||
this.configuredTtl = configuredTtl;
|
||||
+3
-3
@@ -18,9 +18,9 @@ import org.springframework.beans.factory.ObjectProvider;
|
||||
* Metrics decorator for {@link DistributedLockPort}. Metric failures are logged-and-swallowed so
|
||||
* they never affect the lock path. See README for the design rationale.
|
||||
*/
|
||||
final class MeteredDistributedLockPort implements DistributedLockPort {
|
||||
final class MeteredDistributedLock implements DistributedLockPort {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MeteredDistributedLockPort.class);
|
||||
private static final Logger log = LoggerFactory.getLogger(MeteredDistributedLock.class);
|
||||
|
||||
static final String LOCK_ACQUISITION = "lock.acquisition";
|
||||
static final String TAG_OUTCOME = "outcome";
|
||||
@@ -33,7 +33,7 @@ final class MeteredDistributedLockPort implements DistributedLockPort {
|
||||
private final DistributedLockPort delegate;
|
||||
private final MeterRegistry registry; // null when no MeterRegistry on classpath
|
||||
|
||||
MeteredDistributedLockPort(
|
||||
MeteredDistributedLock(
|
||||
DistributedLockPort delegate, ObjectProvider<MeterRegistry> meterRegistryProvider) {
|
||||
this.delegate = delegate;
|
||||
this.registry = meterRegistryProvider.getIfAvailable();
|
||||
+3
-3
@@ -27,7 +27,7 @@ import org.springframework.stereotype.Repository;
|
||||
* lost-update it produces is exactly the case this store exists to prevent.
|
||||
*/
|
||||
@Repository
|
||||
public class DurableOperationStoreAdapter implements DurableOperationStorePort {
|
||||
public class JpaDurableOperationStore implements DurableOperationStorePort {
|
||||
|
||||
private final DurableOperationJpaRepository repository;
|
||||
|
||||
@@ -36,7 +36,7 @@ public class DurableOperationStoreAdapter implements DurableOperationStorePort {
|
||||
*
|
||||
* @param repository the Spring Data access
|
||||
*/
|
||||
public DurableOperationStoreAdapter(DurableOperationJpaRepository repository) {
|
||||
public JpaDurableOperationStore(DurableOperationJpaRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ public class DurableOperationStoreAdapter implements DurableOperationStorePort {
|
||||
DurableOperationId operationId, String principal, Instant now) {
|
||||
return repository
|
||||
.findByOperationIdAndPrincipal(operationId.value(), principal)
|
||||
.map(DurableOperationStoreAdapter::toDomain)
|
||||
.map(JpaDurableOperationStore::toDomain)
|
||||
.map(operation -> expireIfStale(operation, now));
|
||||
}
|
||||
|
||||
+3
-3
@@ -45,14 +45,14 @@ import org.springframework.stereotype.Repository;
|
||||
*/
|
||||
@Repository
|
||||
@ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true")
|
||||
public class OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort {
|
||||
public class JpaOutboxStore implements OutboxAppendPort, OutboxStorePort {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OutboxStoreAdapter.class);
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaOutboxStore.class);
|
||||
|
||||
private final OutboxEventJpaRepository repository;
|
||||
private final OutboxClaimRepository claimRepository;
|
||||
|
||||
public OutboxStoreAdapter(
|
||||
public JpaOutboxStore(
|
||||
OutboxEventJpaRepository repository, OutboxClaimRepository claimRepository) {
|
||||
this.repository = repository;
|
||||
this.claimRepository = claimRepository;
|
||||
+3
-3
@@ -21,7 +21,7 @@ import org.springframework.transaction.support.TransactionTemplate;
|
||||
* pre-built (mutable-template race) and CLAUDE.md for the mode table.
|
||||
*/
|
||||
@Component
|
||||
public class SpringTransactionPort implements TransactionPort {
|
||||
public class SpringTransaction implements TransactionPort {
|
||||
|
||||
/** Upper bound on one {@link #inNew} transaction; the former compensation budget. */
|
||||
static final int REQUIRES_NEW_TIMEOUT_SECONDS = 30;
|
||||
@@ -31,12 +31,12 @@ public class SpringTransactionPort implements TransactionPort {
|
||||
private final TransactionTemplate requiresNewTemplate;
|
||||
private final PersistenceExceptionTranslator exceptionTranslator;
|
||||
|
||||
public SpringTransactionPort(PlatformTransactionManager transactionManager) {
|
||||
public SpringTransaction(PlatformTransactionManager transactionManager) {
|
||||
this(transactionManager, defaultExceptionTranslator());
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public SpringTransactionPort(
|
||||
public SpringTransaction(
|
||||
PlatformTransactionManager transactionManager,
|
||||
PersistenceExceptionTranslator exceptionTranslator) {
|
||||
this.writeTemplate =
|
||||
+1
-1
@@ -222,7 +222,7 @@ class LiveEventLogContractTest {
|
||||
|
||||
private static long allocatePosition(Connection connection, String streamId) throws SQLException {
|
||||
try (PreparedStatement statement =
|
||||
connection.prepareStatement(JpaLiveEventReplayAdapter.ALLOCATE_POSITION_SQL)) {
|
||||
connection.prepareStatement(JpaLiveEventReplay.ALLOCATE_POSITION_SQL)) {
|
||||
statement.setString(1, streamId);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
if (!rows.next()) {
|
||||
|
||||
+6
-6
@@ -4,11 +4,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport;
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
|
||||
import dev.caskeleton.adapter.outbound.support.messaging.JsonIntegrationEventEncoder;
|
||||
import dev.caskeleton.application.idempotency.RequestFingerprint;
|
||||
import dev.caskeleton.application.operation.DurableOperationId;
|
||||
@@ -136,7 +136,7 @@ class DurableOperationSubmissionOutboxIntegrationTest {
|
||||
Throwable thrown = catchThrowable(() -> useCase.handle(command()));
|
||||
|
||||
// then
|
||||
// SpringTransactionPort classifies the commit failure; 23505 is the primary key.
|
||||
// SpringTransaction classifies the commit failure; 23505 is the primary key.
|
||||
assertThat(thrown)
|
||||
.isInstanceOf(PersistenceFailureException.class)
|
||||
.hasMessageContaining("SQLState=23505");
|
||||
@@ -203,7 +203,7 @@ class DurableOperationSubmissionOutboxIntegrationTest {
|
||||
|
||||
@Bean
|
||||
TransactionPort transactionPort(PlatformTransactionManager transactionManager) {
|
||||
return new SpringTransactionPort(transactionManager);
|
||||
return new SpringTransaction(transactionManager);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -212,9 +212,9 @@ class DurableOperationSubmissionOutboxIntegrationTest {
|
||||
OutboxEventJpaRepository outbox,
|
||||
TransactionPort transactions) {
|
||||
return new SubmitDurableOperationUseCase(
|
||||
new DurableOperationStoreAdapter(operations),
|
||||
new JpaDurableOperationStore(operations),
|
||||
// The claim is never exercised here; submission only appends.
|
||||
new OutboxStoreAdapter(outbox, (now, limit) -> List.of()),
|
||||
new JpaOutboxStore(outbox, (now, limit) -> List.of()),
|
||||
new JsonIntegrationEventEncoder(List.of(new DurableOperationSubmittedContract())),
|
||||
transactions,
|
||||
Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
|
||||
+7
-7
@@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.operation;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity;
|
||||
import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport;
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
|
||||
import dev.caskeleton.application.operation.DurableOperationStorePort;
|
||||
import dev.caskeleton.application.operation.testkit.DurableOperationStoreContract;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
@@ -37,7 +37,7 @@ import org.springframework.transaction.PlatformTransactionManager;
|
||||
* constraint violation, so no fake can stand in here.
|
||||
*/
|
||||
@Tag("jpa-contract")
|
||||
class DurableOperationStoreAdapterContractTest extends DurableOperationStoreContract {
|
||||
class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract {
|
||||
|
||||
private static JpaPlatformContractSupport support;
|
||||
private static AnnotationConfigApplicationContext context;
|
||||
@@ -69,7 +69,7 @@ class DurableOperationStoreAdapterContractTest extends DurableOperationStoreCont
|
||||
|
||||
@Override
|
||||
protected DurableOperationStorePort store() {
|
||||
return context.getBean(DurableOperationStoreAdapter.class);
|
||||
return context.getBean(JpaDurableOperationStore.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -86,7 +86,7 @@ class DurableOperationStoreAdapterContractTest extends DurableOperationStoreCont
|
||||
|
||||
private static String migration() throws IOException {
|
||||
try (InputStream resource =
|
||||
DurableOperationStoreAdapterContractTest.class
|
||||
JpaDurableOperationStoreContractTest.class
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("db/migration/postgresql/V11__durable_operation.sql")) {
|
||||
if (resource == null) {
|
||||
@@ -120,13 +120,13 @@ class DurableOperationStoreAdapterContractTest extends DurableOperationStoreCont
|
||||
|
||||
@Bean
|
||||
TransactionPort transactionPort(PlatformTransactionManager transactionManager) {
|
||||
return new SpringTransactionPort(transactionManager);
|
||||
return new SpringTransaction(transactionManager);
|
||||
}
|
||||
|
||||
@Bean
|
||||
DurableOperationStoreAdapter durableOperationStoreAdapter(
|
||||
JpaDurableOperationStore durableOperationStoreAdapter(
|
||||
DurableOperationJpaRepository repository) {
|
||||
return new DurableOperationStoreAdapter(repository);
|
||||
return new JpaDurableOperationStore(repository);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-13
@@ -1,10 +1,10 @@
|
||||
package dev.caskeleton.adapter.outbound.persistence.readiness;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
|
||||
import dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository;
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction;
|
||||
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
|
||||
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
|
||||
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
|
||||
@@ -107,13 +107,12 @@ final class OutboxIntegrationSupport {
|
||||
return tm;
|
||||
});
|
||||
|
||||
// SpringTransactionPort
|
||||
// SpringTransaction
|
||||
ctx.registerBean(
|
||||
"springTransactionPort",
|
||||
SpringTransactionPort.class,
|
||||
"springTransaction",
|
||||
SpringTransaction.class,
|
||||
() ->
|
||||
new SpringTransactionPort(
|
||||
ctx.getBean("transactionManager", JpaTransactionManager.class)));
|
||||
new SpringTransaction(ctx.getBean("transactionManager", JpaTransactionManager.class)));
|
||||
|
||||
// Enable JPA repositories for the outbox package only (avoids scanning
|
||||
// other repositories that have unmet dependencies in this minimal context).
|
||||
@@ -132,12 +131,12 @@ final class OutboxIntegrationSupport {
|
||||
OutboxClaimRepository.class,
|
||||
() -> new PostgreSqlOutboxClaimRepository(sharedEntityManager));
|
||||
|
||||
// OutboxStoreAdapter: @Repository — registered manually (no component scan).
|
||||
// JpaOutboxStore: @Repository — registered manually (no component scan).
|
||||
ctx.registerBean(
|
||||
"outboxStoreAdapter",
|
||||
OutboxStoreAdapter.class,
|
||||
"jpaOutboxStore",
|
||||
JpaOutboxStore.class,
|
||||
() ->
|
||||
new OutboxStoreAdapter(
|
||||
new JpaOutboxStore(
|
||||
ctx.getBean(OutboxEventJpaRepository.class),
|
||||
ctx.getBean(OutboxClaimRepository.class)));
|
||||
|
||||
@@ -170,9 +169,9 @@ final class OutboxIntegrationSupport {
|
||||
* Builds and wires a {@link PublishPendingOutboxEventsUseCase} from beans in the given context.
|
||||
*/
|
||||
static PublishPendingOutboxEventsUseCase relayUseCase(AnnotationConfigApplicationContext ctx) {
|
||||
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
|
||||
JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class);
|
||||
OutboxMessagePublishPort publisher = ctx.getBean(OutboxMessagePublishPort.class);
|
||||
TransactionPort tx = ctx.getBean(SpringTransactionPort.class);
|
||||
TransactionPort tx = ctx.getBean(SpringTransaction.class);
|
||||
Clock clock = ctx.getBean(Clock.class);
|
||||
return new PublishPendingOutboxEventsUseCase(
|
||||
store,
|
||||
|
||||
+10
-10
@@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLockAdapter;
|
||||
import dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLock;
|
||||
import dev.caskeleton.application.lock.DistributedLock;
|
||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||
import java.time.Duration;
|
||||
@@ -47,8 +47,8 @@ class PostgreSqlDistributedLockIntegrationTest {
|
||||
DefaultLockRepository repositoryA = repository(dataSource);
|
||||
DefaultLockRepository repositoryB = repository(dataSource);
|
||||
try {
|
||||
LockRegistryDistributedLockAdapter adapterA = adapter(repositoryA, ttl);
|
||||
LockRegistryDistributedLockAdapter adapterB = adapter(repositoryB, ttl);
|
||||
LockRegistryDistributedLock adapterA = adapter(repositoryA, ttl);
|
||||
LockRegistryDistributedLock adapterB = adapter(repositoryB, ttl);
|
||||
String key = "distributed-lock-mutual-exclusion-" + System.nanoTime();
|
||||
|
||||
DistributedLock first = adapterA.tryAcquire(key, Duration.ofSeconds(1), ttl);
|
||||
@@ -74,8 +74,8 @@ class PostgreSqlDistributedLockIntegrationTest {
|
||||
DefaultLockRepository repositoryA = repository(dataSource);
|
||||
DefaultLockRepository repositoryB = repository(dataSource);
|
||||
try {
|
||||
LockRegistryDistributedLockAdapter adapterA = adapter(repositoryA, ttl);
|
||||
LockRegistryDistributedLockAdapter adapterB = adapter(repositoryB, ttl);
|
||||
LockRegistryDistributedLock adapterA = adapter(repositoryA, ttl);
|
||||
LockRegistryDistributedLock adapterB = adapter(repositoryB, ttl);
|
||||
String key = "distributed-lock-expired-lease-" + System.nanoTime();
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@@ -96,8 +96,8 @@ class PostgreSqlDistributedLockIntegrationTest {
|
||||
DefaultLockRepository repositoryA = repository(dataSource);
|
||||
DefaultLockRepository repositoryB = repository(dataSource);
|
||||
try {
|
||||
LockRegistryDistributedLockAdapter adapterA = adapter(repositoryA, ttl);
|
||||
LockRegistryDistributedLockAdapter adapterB = adapter(repositoryB, ttl);
|
||||
LockRegistryDistributedLock adapterA = adapter(repositoryA, ttl);
|
||||
LockRegistryDistributedLock adapterB = adapter(repositoryB, ttl);
|
||||
String key = "distributed-lock-stale-close-" + System.nanoTime();
|
||||
|
||||
DistributedLock stale = adapterA.tryAcquire(key, Duration.ofSeconds(1), ttl);
|
||||
@@ -116,7 +116,7 @@ class PostgreSqlDistributedLockIntegrationTest {
|
||||
}
|
||||
|
||||
private static DistributedLock acquireWithin(
|
||||
LockRegistryDistributedLockAdapter adapter, String key, Duration leaseTtl, Duration bound)
|
||||
LockRegistryDistributedLock adapter, String key, Duration leaseTtl, Duration bound)
|
||||
throws InterruptedException {
|
||||
long deadline = System.nanoTime() + bound.toNanos();
|
||||
LockAcquisitionTimeoutException lastTimeout = null;
|
||||
@@ -132,9 +132,9 @@ class PostgreSqlDistributedLockIntegrationTest {
|
||||
"could not acquire distributed lock within " + bound + " after lease expiry", lastTimeout);
|
||||
}
|
||||
|
||||
private static LockRegistryDistributedLockAdapter adapter(
|
||||
private static LockRegistryDistributedLock adapter(
|
||||
DefaultLockRepository repository, Duration ttl) {
|
||||
return new LockRegistryDistributedLockAdapter(new JdbcLockRegistry(repository, ttl), ttl);
|
||||
return new LockRegistryDistributedLock(new JdbcLockRegistry(repository, ttl), ttl);
|
||||
}
|
||||
|
||||
private static DefaultLockRepository repository(DataSource dataSource) {
|
||||
|
||||
+9
-9
@@ -4,9 +4,9 @@ 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.adapter.outbound.persistence.fileserver.JpaFileMetadataStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuotaService;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSessionStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuota;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession;
|
||||
import dev.caskeleton.application.fileserver.api.ContentKey;
|
||||
import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.FileState;
|
||||
@@ -60,9 +60,9 @@ class PostgreSqlFileserverMetadataStoreIntegrationTest {
|
||||
private static FileserverJpaTestContext context;
|
||||
private static JdbcTemplate jdbc;
|
||||
private static TransactionTemplate transactions;
|
||||
private static JpaFileMetadataStore files;
|
||||
private static JpaUploadSessionStore uploads;
|
||||
private static JpaFileQuotaService quota;
|
||||
private static JpaFileMetadata files;
|
||||
private static JpaUploadSession uploads;
|
||||
private static JpaFileQuota quota;
|
||||
|
||||
@BeforeAll
|
||||
static void startAndMigratePostgreSql() {
|
||||
@@ -79,9 +79,9 @@ class PostgreSqlFileserverMetadataStoreIntegrationTest {
|
||||
jdbc = new JdbcTemplate(postgres.dataSource());
|
||||
context = new FileserverJpaTestContext(postgres.dataSource(), Clock.systemUTC());
|
||||
transactions = context.transactions();
|
||||
files = context.bean(JpaFileMetadataStore.class);
|
||||
uploads = context.bean(JpaUploadSessionStore.class);
|
||||
quota = context.bean(JpaFileQuotaService.class);
|
||||
files = context.bean(JpaFileMetadata.class);
|
||||
uploads = context.bean(JpaUploadSession.class);
|
||||
quota = context.bean(JpaFileQuota.class);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
|
||||
+15
-15
@@ -4,13 +4,13 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaCleanupQueue;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaContentReferenceLedger;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadataStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuotaService;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaCommitGateway;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaimGateway;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuota;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaCommit;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaim;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaRecoveryQueue;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaStagingUploadLocator;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSessionStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession;
|
||||
import dev.caskeleton.application.fileserver.api.ContentKey;
|
||||
import dev.caskeleton.application.fileserver.api.FileId;
|
||||
import dev.caskeleton.application.fileserver.api.FileState;
|
||||
@@ -59,13 +59,13 @@ class PostgreSqlFileserverReclamationIntegrationTest {
|
||||
private static FileserverJpaTestContext context;
|
||||
private static JdbcTemplate jdbc;
|
||||
private static TransactionTemplate transactions;
|
||||
private static JpaFileMetadataStore files;
|
||||
private static JpaUploadSessionStore uploads;
|
||||
private static JpaFileQuotaService quota;
|
||||
private static JpaFileMetadata files;
|
||||
private static JpaUploadSession uploads;
|
||||
private static JpaFileQuota quota;
|
||||
private static JpaCleanupQueue cleanupQueue;
|
||||
private static JpaRecoveryQueue recoveryQueue;
|
||||
private static JpaQuotaCommitGateway quotaCommit;
|
||||
private static JpaQuotaReclaimGateway quotaReclaim;
|
||||
private static JpaQuotaCommit quotaCommit;
|
||||
private static JpaQuotaReclaim quotaReclaim;
|
||||
private static JpaContentReferenceLedger ledger;
|
||||
private static JpaStagingUploadLocator stagingLocator;
|
||||
|
||||
@@ -84,13 +84,13 @@ class PostgreSqlFileserverReclamationIntegrationTest {
|
||||
jdbc = new JdbcTemplate(postgres.dataSource());
|
||||
context = new FileserverJpaTestContext(postgres.dataSource(), Clock.systemUTC());
|
||||
transactions = context.transactions();
|
||||
files = context.bean(JpaFileMetadataStore.class);
|
||||
uploads = context.bean(JpaUploadSessionStore.class);
|
||||
quota = context.bean(JpaFileQuotaService.class);
|
||||
files = context.bean(JpaFileMetadata.class);
|
||||
uploads = context.bean(JpaUploadSession.class);
|
||||
quota = context.bean(JpaFileQuota.class);
|
||||
cleanupQueue = context.bean(JpaCleanupQueue.class);
|
||||
recoveryQueue = context.bean(JpaRecoveryQueue.class);
|
||||
quotaCommit = context.bean(JpaQuotaCommitGateway.class);
|
||||
quotaReclaim = context.bean(JpaQuotaReclaimGateway.class);
|
||||
quotaCommit = context.bean(JpaQuotaCommit.class);
|
||||
quotaReclaim = context.bean(JpaQuotaReclaim.class);
|
||||
ledger = context.bean(JpaContentReferenceLedger.class);
|
||||
stagingLocator = context.bean(JpaStagingUploadLocator.class);
|
||||
}
|
||||
|
||||
+3
-3
@@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore;
|
||||
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlIdempotencyStore;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyClaimRequest;
|
||||
@@ -42,7 +42,7 @@ class PostgreSqlIdempotencyIntegrationTest {
|
||||
private static PostgreSqlReadinessSupport postgres;
|
||||
private static JdbcTemplate jdbc;
|
||||
private static TransactionTemplate transactions;
|
||||
private static PostgreSqlOwnerSafeIdempotencyStore store;
|
||||
private static PostgreSqlIdempotencyStore store;
|
||||
|
||||
@BeforeAll
|
||||
static void startAndMigratePostgreSql() {
|
||||
@@ -58,7 +58,7 @@ class PostgreSqlIdempotencyIntegrationTest {
|
||||
|
||||
jdbc = new JdbcTemplate(postgres.dataSource());
|
||||
transactions = new TransactionTemplate(new DataSourceTransactionManager(postgres.dataSource()));
|
||||
store = new PostgreSqlOwnerSafeIdempotencyStore(jdbc);
|
||||
store = new PostgreSqlIdempotencyStore(jdbc);
|
||||
jdbc.update(
|
||||
"update capability_schema_registry set lifecycle_state = 'ACTIVE' "
|
||||
+ "where capability_id = 'jpa-idempotency-owner-safe-v2'");
|
||||
|
||||
+7
-2
@@ -49,7 +49,8 @@ class PostgreSqlMigrationIntegrationTest {
|
||||
|
||||
assertThat(appliedVersions(postgres, "flyway_schema_history"))
|
||||
.containsExactly(
|
||||
"1", "3", "4", "5", "6", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18");
|
||||
"1", "3", "4", "5", "6", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18",
|
||||
"19");
|
||||
assertThat(
|
||||
singleValue(
|
||||
postgres,
|
||||
@@ -233,6 +234,9 @@ class PostgreSqlMigrationIntegrationTest {
|
||||
assertColumn(database, "payload_schema_hash", "character varying", 64);
|
||||
assertCanonicalOutboxConstraintsValidated(database);
|
||||
|
||||
// A pre-canonical row survives V19 only as history: PUBLISHED. An unpublished one is what V19
|
||||
// refuses (ck_outbox_event_canonical_unless_published), since nothing can deliver it any
|
||||
// more.
|
||||
database.execute(
|
||||
"""
|
||||
insert into outbox_event (
|
||||
@@ -240,7 +244,7 @@ class PostgreSqlMigrationIntegrationTest {
|
||||
status, attempt_count, next_attempt_at, correlation_id, idempotency_key
|
||||
) values (
|
||||
'legacy-1', 'aggregate-1', 'LegacyEvent', '{}', clock_timestamp(),
|
||||
'PENDING', 0, clock_timestamp(), 'correlation-1', 'legacy-1'
|
||||
'PUBLISHED', 0, clock_timestamp(), 'correlation-1', 'legacy-1'
|
||||
)
|
||||
""");
|
||||
|
||||
@@ -311,6 +315,7 @@ class PostgreSqlMigrationIntegrationTest {
|
||||
"ck_outbox_event_canonical_partition_key",
|
||||
"ck_outbox_event_canonical_required_text",
|
||||
"ck_outbox_event_canonical_shape",
|
||||
"ck_outbox_event_canonical_unless_published",
|
||||
"ck_outbox_event_canonical_versions");
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user