From 0579935746bb830ab4652e1e15b1e0045cfc0e36 Mon Sep 17 00:00:00 2001 From: donghyeon-ka Date: Tue, 29 Sep 2026 14:54:06 +0900 Subject: [PATCH] =?UTF-8?q?review-followup=20Wave=203=20=EB=9D=BC=EC=9A=B4?= =?UTF-8?q?=EB=93=9C=203(P28=C2=B7P29):=20fileserver=20use=20case=C2=B7fil?= =?UTF-8?q?e:*=20=EA=B6=8C=ED=95=9C,=20=EB=B3=B4=EC=95=88=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20primitive=20=EA=B3=B5=EC=9A=A9=ED=99=94,=20jvm-test?= =?UTF-8?q?-suite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 결정 32: fileserver transport 연산 21개를 `port.in` use case로, 쓰기·읽기에 `file:*` 권한(소유자·tenant 정책은 유지), inbound 서비스 이름 `*UseCase`, 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) --- docs/architecture/jpa-api-surface.txt | 14 +- .../persistence-fileserver-api-surface.txt | 10 +- docs/capability-status.md | 5 + docs/fileserver/configuration.md | 7 + docs/fileserver/design-deviations.md | 68 +-- docs/jpa/observability.md | 2 +- docs/jpa/runbooks.md | 2 +- docs/jpa/transaction-guide.md | 4 +- .../W3-P28.md | 25 ++ .../W3-P29.md | 18 + .../2026-09-25-review-followup-status.md | 30 +- docs/study/postgresql-jpa-walkthrough.ko.md | 22 +- .../__pycache__/by_area.cpython-312.pyc | Bin 0 -> 6575 bytes docs/web/repository-adaptation.md | 4 +- infra/keycloak/README.md | 6 + infra/keycloak/realms/ca-skeleton-realm.json | 22 +- src/adapter/inbound/graphql/build.gradle | 15 +- .../admin/FileserverAdminController.java | 80 +++- .../config/BlockingTransferExecutor.java | 12 +- .../controller/FileDownloadController.java | 43 +- .../controller/FileUploadController.java | 28 +- .../draft12/Draft12UploadController.java | 74 ++-- .../lifecycle/FileLifecycleController.java | 49 ++- .../problem/FileserverExceptionHandler.java | 6 - .../web/fileserver/tus/TusController.java | 78 ++-- .../admin/FileserverAdminControllerTest.java | 2 +- ...ngTransferExecutorSecurityContextTest.java | 79 ++++ .../FileDownloadControllerContractTest.java | 5 +- .../controller/FileUploadControllerTest.java | 2 +- .../draft12/Draft12ProtocolTest.java | 5 +- .../nginx/NginxDownloadDelegationTest.java | 5 +- .../FileserverHardeningContractTest.java | 7 +- .../InMemoryUploadApplicationService.java | 41 +- .../testkit/RecordingAdminService.java | 63 ++- .../testkit/RecordingFinalizeService.java | 17 +- .../testkit/RecordingUploadService.java | 16 +- .../testkit/StubDownloadService.java | 38 +- .../tus/TusProtocolContractTest.java | 7 +- src/adapter/inbound/web/build.gradle | 46 ++- src/adapter/inbound/websocket/build.gradle | 51 ++- ...Adapter.java => StructuredAdminAudit.java} | 2 +- ...er.java => StructuredFileserverAudit.java} | 2 +- ...FileserverCapabilityAutoConfiguration.java | 1 - ...eserverDownloadLifecycleConfiguration.java | 70 ---- ...serverMaintenanceServiceConfiguration.java | 48 --- .../FileserverSecurityConfiguration.java | 8 +- ...FileserverStorageGatewayConfiguration.java | 16 +- ...eserverStorageOperationsConfiguration.java | 17 +- .../FileserverVerificationConfiguration.java | 2 +- ...ctory.java => RandomUploadIdentifier.java} | 2 +- .../local/AtomicMoveContentPublisher.java | 1 + .../local/ContentPublishVerification.java | 1 + ...tGateway.java => LocalCleanupContent.java} | 4 +- ...tentGateway.java => LocalCopyContent.java} | 7 +- ...nScanAdapter.java => LocalOrphanScan.java} | 4 +- ...e.java => LocalReconciliationContent.java} | 4 +- .../local/LocalStorageCapabilityProbe.java | 1 + .../platform/local/LocalStorageFailures.java | 17 + ...thAdapter.java => LocalStorageHealth.java} | 4 +- ...UsageProbe.java => LocalStorageUsage.java} | 4 +- ...ntGateway.java => LocalUploadContent.java} | 4 +- ...geGateway.java => LocalUploadStorage.java} | 4 +- .../local/SafeFileChannelFactory.java | 226 ++-------- .../platform/verification/FileVerifier.java | 23 ++ .../verification/FilenamePolicyVerifier.java | 1 - .../platform/verification/LengthVerifier.java | 1 - .../verification/MediaTypeVerifier.java | 1 - .../verification/ScriptableContentPolicy.java | 1 - .../platform/verification/Sha256Verifier.java | 1 - .../verification/VerificationCoordinator.java | 1 - ...pterTest.java => LocalOrphanScanTest.java} | 16 +- .../local/LocalStorageFailuresTest.java | 74 ++++ .../LocalStorageGatewayContractTest.java | 14 +- .../VerificationCoordinatorTest.java | 1 - src/adapter/outbound/httpclient/build.gradle | 26 +- .../platform/dispatch/ProviderRuntime.java | 21 + .../dispatch/ProviderRuntimeRegistry.java | 30 +- .../ses/SesNotificationProviderAdapter.java | 9 +- .../dispatch/ProviderRuntimeRegistryTest.java | 41 +- .../SesNotificationProviderAdapterTest.java | 46 +++ .../outbound/objectstorage/build.gradle | 23 +- .../FileserverJpaMetadataStoreConfig.java | 44 ++ .../FileserverJpaPersistenceConfig.java | 15 +- .../FileserverJpaQueueStoreConfig.java | 46 +++ .../fileserver/JpaCleanupQueue.java | 8 - .../fileserver/JpaContentReferenceLedger.java | 8 - ...etadataStore.java => JpaFileMetadata.java} | 12 +- ...ileQuotaService.java => JpaFileQuota.java} | 12 +- ...CommitGateway.java => JpaQuotaCommit.java} | 12 +- ...claimGateway.java => JpaQuotaReclaim.java} | 12 +- .../fileserver/JpaRecoveryQueue.java | 8 - .../fileserver/JpaStagingUploadLocator.java | 8 - ...essionStore.java => JpaUploadSession.java} | 12 +- .../outbound/persistence-jpa/CLAUDE.md | 14 +- .../outbound/persistence-jpa/README.md | 26 +- .../outbound/persistence-jpa/build.gradle | 37 +- ...rt.java => DomainContextAuditContext.java} | 4 +- .../PostgreSqlIdempotencyStoreConfig.java | 4 +- .../config/JpaAdapterComponentsConfig.java | 6 +- ...e.java => PostgreSqlIdempotencyStore.java} | 6 +- ...ayAdapter.java => JpaLiveEventReplay.java} | 4 +- .../DistributedLockPersistenceConfig.java | 10 +- ....java => LockRegistryDistributedLock.java} | 4 +- ...kPort.java => MeteredDistributedLock.java} | 6 +- ...ter.java => JpaDurableOperationStore.java} | 6 +- ...xStoreAdapter.java => JpaOutboxStore.java} | 6 +- ...actionPort.java => SpringTransaction.java} | 6 +- .../liveevent/LiveEventLogContractTest.java | 2 +- ...rationSubmissionOutboxIntegrationTest.java | 12 +- ...JpaDurableOperationStoreContractTest.java} | 14 +- .../readiness/OutboxIntegrationSupport.java | 25 +- ...tgreSqlDistributedLockIntegrationTest.java | 20 +- ...ileserverMetadataStoreIntegrationTest.java | 18 +- ...lFileserverReclamationIntegrationTest.java | 30 +- .../PostgreSqlIdempotencyIntegrationTest.java | 6 +- .../PostgreSqlMigrationIntegrationTest.java | 9 +- ...ficationBackgroundPassIntegrationTest.java | 4 +- ...boxClaimAndMaintenanceIntegrationTest.java | 6 +- ...lOutboxConcurrentRelayIntegrationTest.java | 6 +- ...eSqlOutboxRowLifecycleIntegrationTest.java | 16 +- .../PostgreSqlTransactionIntegrationTest.java | 14 +- .../CandidateAdapterCompositionTest.java | 2 +- ...ava => DomainContextAuditContextTest.java} | 8 +- .../PersistenceJpaCapabilityAssemblyTest.java | 2 +- .../PostgreSqlIdempotencyStoreConfigTest.java | 4 +- .../OwnerSafeIdempotencyPreconditionTest.java | 3 +- ... => JpaLiveEventReplayActivationTest.java} | 10 +- .../DistributedLockPersistenceConfigTest.java | 2 +- ...a => LockRegistryDistributedLockTest.java} | 18 +- ...=> MeteredDistributedLockLoggingTest.java} | 7 +- ...t.java => MeteredDistributedLockTest.java} | 53 +-- .../AppliedMigrationImmutabilityTest.java | 7 +- ...apterTest.java => JpaOutboxStoreTest.java} | 12 +- .../jpa/OutboxSwitchWiringContractTest.java | 2 +- .../PersistenceTransactionOwnershipTest.java | 14 +- ...rtTest.java => SpringTransactionTest.java} | 22 +- .../resources/db/applied-migrations.sha256 | 5 + .../outbound/persistence-mongo/build.gradle | 54 ++- src/adapter/outbound/redis-sdk/README.md | 5 +- src/adapter/outbound/redis-sdk/build.gradle | 6 +- src/adapter/outbound/support/CLAUDE.md | 5 + .../filesystem}/SecureDirectoryWalk.java | 38 +- .../support/filesystem/SecureFileAccess.java | 273 ++++++++++++ .../filesystem}/SecureDirectoryWalkTest.java | 2 +- .../filesystem/SecureFileAccessTest.java | 170 ++++++++ src/app-bootstrap/build.gradle | 60 ++- .../ApplicationBoundaryArchitectureTest.java | 7 +- ...mpositionRootBoundaryArchitectureTest.java | 4 +- ...ileserverUseCaseContractDeviationTest.java | 41 +- .../architecture/NamingConventionTest.java | 2 +- .../FileserverCompositionIntegrationTest.java | 108 ++++- .../src/main/resources/config/security.yml | 10 + src/application-core/README.md | 4 +- .../transaction/TransactionPort.java | 2 +- .../transaction/IsolationTest.java | 4 +- .../fileserver/admin/AdminAudit.java | 74 ++++ .../CleanupUploadsApplicationUseCase.java | 54 +++ .../admin/DefaultFileserverAdminService.java | 272 ------------ .../admin/FileserverAdminService.java | 34 -- .../ForceDeleteFileApplicationUseCase.java | 81 ++++ ...RuntimeCapabilitiesApplicationUseCase.java | 40 ++ .../GetStorageHealthApplicationUseCase.java | 45 ++ ...stIncompleteUploadsApplicationUseCase.java | 72 ++++ .../admin/ListOrphansApplicationUseCase.java | 41 ++ .../ReconcileOrphansApplicationUseCase.java | 88 ++++ .../admin/ReverifyFileApplicationUseCase.java | 79 ++++ .../fileserver/api/metadata/FileRecords.java | 53 +++ .../fileserver/api/security/FileVerifier.java | 17 - .../DefaultDownloadApplicationService.java | 149 ------- .../DescribeFileApplicationUseCase.java | 56 +++ .../download/DownloadApplicationService.java | 35 -- .../fileserver/download/DownloadRequest.java | 16 - ...OpenDownloadContentApplicationUseCase.java | 41 ++ .../PrepareDownloadApplicationUseCase.java | 82 ++++ ...sferDownloadContentApplicationUseCase.java | 64 +++ .../lifecycle/ContentPreconditions.java | 27 ++ .../lifecycle/CopyFileApplicationUseCase.java | 172 ++++++++ .../DefaultFileLifecycleService.java | 270 ------------ .../DeleteFileApplicationUseCase.java | 102 +++++ .../lifecycle/FileLifecycleService.java | 31 -- .../lifecycle/MoveFileApplicationUseCase.java | 59 +++ .../port/in/AppendUploadCommand.java | 35 ++ .../port/in/AppendUploadUseCase.java | 8 + .../port/in/CancelUploadCommand.java | 20 + .../port/in/CancelUploadUseCase.java | 6 + .../port/in/CleanupUploadsCommand.java | 20 + .../port/in/CleanupUploadsUseCase.java | 8 + .../in}/CopyFileCommand.java | 19 +- .../fileserver/port/in/CopyFileUseCase.java | 7 + .../port/in/CreateUploadCommand.java | 21 + .../port/in/CreateUploadUseCase.java | 8 + .../fileserver/port/in/DeleteFileCommand.java | 24 ++ .../fileserver/port/in/DeleteFileUseCase.java | 7 + .../fileserver/port/in/DescribeFileQuery.java | 20 + .../port/in/DescribeFileUseCase.java | 7 + .../port/in/FinalizeUploadCommand.java | 24 ++ .../port/in/FinalizeUploadUseCase.java | 7 + .../in}/ForceDeleteCommand.java | 12 +- .../port/in/ForceDeleteFileUseCase.java | 6 + .../port/in/GetRuntimeCapabilitiesQuery.java | 17 + .../in/GetRuntimeCapabilitiesUseCase.java | 8 + .../port/in/GetStorageHealthQuery.java | 17 + .../port/in/GetStorageHealthUseCase.java | 8 + .../port/in/GetUploadStatusQuery.java | 20 + .../port/in/GetUploadStatusUseCase.java | 8 + .../port/in/ListIncompleteUploadsQuery.java | 18 + .../port/in/ListIncompleteUploadsUseCase.java | 9 + .../fileserver/port/in/ListOrphansQuery.java | 18 + .../port/in/ListOrphansUseCase.java | 8 + .../fileserver/port/in/MoveFileCommand.java | 31 ++ .../fileserver/port/in/MoveFileUseCase.java | 7 + .../port/in/OpenDownloadContentQuery.java | 21 + .../port/in/OpenDownloadContentUseCase.java | 8 + .../in}/OrphanReconcileCommand.java | 21 +- .../port/in/PrepareDownloadQuery.java | 20 + .../port/in/PrepareDownloadUseCase.java | 8 + .../port/in/ReconcileOrphansUseCase.java | 8 + .../port/in/ReverifyFileCommand.java | 20 + .../port/in/ReverifyFileUseCase.java | 7 + .../port/in/TransferDownloadContentQuery.java | 24 ++ .../in/TransferDownloadContentUseCase.java | 8 + .../fileserver/port/in/UploadFileCommand.java | 33 ++ .../fileserver/port/in/UploadFileUseCase.java | 7 + .../AppendUploadApplicationUseCase.java | 170 ++++++++ .../CancelUploadApplicationUseCase.java | 73 ++++ .../CreateUploadApplicationUseCase.java | 204 +++++++++ .../DefaultSingleShotUploadService.java | 60 --- .../DefaultUploadApplicationService.java | 387 ------------------ ... => FinalizeUploadApplicationUseCase.java} | 28 +- .../upload/FinalizeUploadService.java | 25 -- .../GetUploadStatusApplicationUseCase.java | 72 ++++ .../upload/SingleShotUploadService.java | 27 -- .../upload/UploadApplicationService.java | 46 --- .../upload/UploadFileApplicationUseCase.java | 99 +++++ .../fileserver/upload/UploadSessions.java | 79 ++++ ....java => FileserverAdminUseCasesTest.java} | 131 +++--- ...iceTest.java => DownloadUseCasesTest.java} | 39 +- ...st.java => FileLifecycleUseCasesTest.java} | 97 +++-- .../testkit/InMemoryUploadSessionStore.java | 11 + .../DefaultSingleShotUploadServiceTest.java | 142 ------- ...FinalizeUploadApplicationUseCaseTest.java} | 133 +++--- ....java => ResumableUploadUseCasesTest.java} | 17 +- .../UploadFileApplicationUseCaseTest.java | 98 +++++ .../fileserver/upload/UploadUseCases.java | 92 +++++ src/build-logic/README.md | 3 +- src/build-logic/build.gradle | 4 - .../AuxiliarySourceSetExtension.java | 92 ----- .../auxiliary/AuxiliarySourceSetPlugin.java | 11 - .../auxiliary/AuxiliarySourceSetSpec.java | 48 --- .../java/JavaConventionsPlugin.java | 21 + .../strictlane/StrictTestLaneExtension.java | 10 +- .../strictlane/StrictTestLanePlugin.java | 22 +- .../AuxiliarySourceSetConventionTest.java | 145 ------- .../StrictTestLaneConventionTest.java | 40 ++ ...serverAdminActionUseCaseConfiguration.java | 95 +++++ ...leserverAdminReadUseCaseConfiguration.java | 66 +++ .../FileserverFileUseCaseConfiguration.java | 120 ++++++ .../FileserverPlatformAutoConfiguration.java | 6 +- .../FileserverUploadSupportConfiguration.java | 63 +++ ...FileserverUploadUseCaseConfiguration.java} | 148 ++++--- .../FileserverRuntimeAssemblyTest.java | 69 +++- .../IdempotencyAutoConfigurationTest.java | 2 +- .../grpc-operation-ledger-jpa/build.gradle | 15 +- src/messaging/messaging-kafka/build.gradle | 16 +- .../build.gradle | 15 +- .../messaging/outbox/OutboxPostgresIT.java | 38 +- .../build.gradle | 15 +- src/sample-portfolio/build.gradle | 38 +- .../event/PortfolioEventContracts.java | 8 - .../event/PosterEventPublisher.java | 10 - .../event/PosterImageAttachedPayload.java | 12 - .../PosterImageAttachmentReadyPayload.java | 4 +- .../SampleApplicationUseCaseConfig.java | 6 - .../domain/poster/PosterImageAttached.java | 17 - .../poster.image-attached/v1.schema.json | 23 -- 275 files changed, 5838 insertions(+), 3312 deletions(-) create mode 100644 docs/reviews/2026-09-25-review-followup-results/W3-P28.md create mode 100644 docs/reviews/2026-09-25-review-followup-results/W3-P29.md create mode 100644 docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/by_area.cpython-312.pyc create mode 100644 src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutorSecurityContextTest.java rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/{StructuredAdminAuditAdapter.java => StructuredAdminAudit.java} (94%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/{StructuredFileserverAuditAdapter.java => StructuredFileserverAudit.java} (92%) delete mode 100644 src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverDownloadLifecycleConfiguration.java rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/{RandomUploadIdentifierFactory.java => RandomUploadIdentifier.java} (92%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalCleanupContentGateway.java => LocalCleanupContent.java} (89%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalCopyContentGateway.java => LocalCopyContent.java} (93%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalOrphanScanAdapter.java => LocalOrphanScan.java} (98%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalReconciliationContentProbe.java => LocalReconciliationContent.java} (95%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalStorageHealthAdapter.java => LocalStorageHealth.java} (95%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalStorageUsageProbe.java => LocalStorageUsage.java} (92%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalUploadContentGateway.java => LocalUploadContent.java} (97%) rename src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalUploadStorageGateway.java => LocalUploadStorage.java} (93%) create mode 100644 src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FileVerifier.java rename src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/{LocalOrphanScanAdapterTest.java => LocalOrphanScanTest.java} (93%) create mode 100644 src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailuresTest.java create mode 100644 src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaMetadataStoreConfig.java create mode 100644 src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaQueueStoreConfig.java rename src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/{JpaFileMetadataStore.java => JpaFileMetadata.java} (94%) rename src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/{JpaFileQuotaService.java => JpaFileQuota.java} (88%) rename src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/{JpaQuotaCommitGateway.java => JpaQuotaCommit.java} (92%) rename src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/{JpaQuotaReclaimGateway.java => JpaQuotaReclaim.java} (84%) rename src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/{JpaUploadSessionStore.java => JpaUploadSession.java} (94%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/{DomainContextAuditContextPort.java => DomainContextAuditContext.java} (86%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/{PostgreSqlOwnerSafeIdempotencyStore.java => PostgreSqlIdempotencyStore.java} (99%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/{JpaLiveEventReplayAdapter.java => JpaLiveEventReplay.java} (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/{LockRegistryDistributedLockAdapter.java => LockRegistryDistributedLock.java} (94%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/{MeteredDistributedLockPort.java => MeteredDistributedLock.java} (96%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/{DurableOperationStoreAdapter.java => JpaDurableOperationStore.java} (97%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/{OutboxStoreAdapter.java => JpaOutboxStore.java} (98%) rename src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/{SpringTransactionPort.java => SpringTransaction.java} (96%) rename src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/{DurableOperationStoreAdapterContractTest.java => JpaDurableOperationStoreContractTest.java} (91%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/{DomainContextAuditContextPortTest.java => DomainContextAuditContextTest.java} (87%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/{JpaLiveEventReplayAdapterActivationTest.java => JpaLiveEventReplayActivationTest.java} (95%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/{LockRegistryDistributedLockAdapterTest.java => LockRegistryDistributedLockTest.java} (89%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/{MeteredDistributedLockPortLoggingTest.java => MeteredDistributedLockLoggingTest.java} (94%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/{MeteredDistributedLockPortTest.java => MeteredDistributedLockTest.java} (78%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/{OutboxStoreAdapterTest.java => JpaOutboxStoreTest.java} (97%) rename src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/{SpringTransactionPortTest.java => SpringTransactionTest.java} (92%) rename src/adapter/outbound/{fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local => support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem}/SecureDirectoryWalk.java (88%) create mode 100644 src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccess.java rename src/adapter/outbound/{fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local => support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem}/SecureDirectoryWalkTest.java (96%) create mode 100644 src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccessTest.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/AdminAudit.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/CleanupUploadsApplicationUseCase.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/DefaultFileserverAdminService.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/FileserverAdminService.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteFileApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetRuntimeCapabilitiesApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetStorageHealthApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListIncompleteUploadsApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListOrphansApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReconcileOrphansApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReverifyFileApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileRecords.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileVerifier.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DefaultDownloadApplicationService.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DescribeFileApplicationUseCase.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadApplicationService.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadRequest.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/OpenDownloadContentApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/PrepareDownloadApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/TransferDownloadContentApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/ContentPreconditions.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DefaultFileLifecycleService.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DeleteFileApplicationUseCase.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleService.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsUseCase.java rename src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/{lifecycle => port/in}/CopyFileCommand.java (50%) create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadUseCase.java rename src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/{admin => port/in}/ForceDeleteCommand.java (68%) create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentUseCase.java rename src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/{admin => port/in}/OrphanReconcileCommand.java (61%) create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReconcileOrphansUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentQuery.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileCommand.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CancelUploadApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadService.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java rename src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/{DefaultFinalizeUploadService.java => FinalizeUploadApplicationUseCase.java} (93%) delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadService.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/GetUploadStatusApplicationUseCase.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/SingleShotUploadService.java delete mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCase.java create mode 100644 src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java rename src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/{FileserverAdminServiceTest.java => FileserverAdminUseCasesTest.java} (71%) rename src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/{DownloadApplicationServiceTest.java => DownloadUseCasesTest.java} (67%) rename src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/{FileLifecycleServiceTest.java => FileLifecycleUseCasesTest.java} (75%) delete mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java rename src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/{FinalizeUploadServiceTest.java => FinalizeUploadApplicationUseCaseTest.java} (75%) rename src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/{UploadApplicationServiceTest.java => ResumableUploadUseCasesTest.java} (96%) create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java create mode 100644 src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadUseCases.java delete mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetExtension.java delete mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetPlugin.java delete mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetSpec.java delete mode 100644 src/build-logic/src/test/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetConventionTest.java create mode 100644 src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminActionUseCaseConfiguration.java create mode 100644 src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminReadUseCaseConfiguration.java create mode 100644 src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java create mode 100644 src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadSupportConfiguration.java rename src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/{FileserverUploadServiceConfiguration.java => FileserverUploadUseCaseConfiguration.java} (51%) delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java delete mode 100644 src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttached.java delete mode 100644 src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json diff --git a/docs/architecture/jpa-api-surface.txt b/docs/architecture/jpa-api-surface.txt index df856a74..578a5566 100644 --- a/docs/architecture/jpa-api-surface.txt +++ b/docs/architecture/jpa-api-surface.txt @@ -43,7 +43,7 @@ dev.caskeleton.adapter.outbound.persistence.api.query.SortDirection dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort dev.caskeleton.adapter.outbound.persistence.audit.AuditableEntity -dev.caskeleton.adapter.outbound.persistence.audit.DomainContextAuditContextPort +dev.caskeleton.adapter.outbound.persistence.audit.DomainContextAuditContext dev.caskeleton.adapter.outbound.persistence.cache.CacheConcurrencyStrategy dev.caskeleton.adapter.outbound.persistence.cache.CacheRegionCatalog dev.caskeleton.adapter.outbound.persistence.cache.HibernateCacheGuard @@ -103,12 +103,12 @@ dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream -dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore -dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplayAdapter +dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlIdempotencyStore +dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplay dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity dev.caskeleton.adapter.outbound.persistence.lock.DistributedLockPersistenceConfig -dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLockAdapter +dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLock dev.caskeleton.adapter.outbound.persistence.lock.LockSettings dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy dev.caskeleton.adapter.outbound.persistence.migration.SchemaManagementMode @@ -117,13 +117,13 @@ dev.caskeleton.adapter.outbound.persistence.observation.LowCardinality dev.caskeleton.adapter.outbound.persistence.observation.MicrometerQueryObservation dev.caskeleton.adapter.outbound.persistence.observation.SqlDiagnosticRedactor dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository -dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationStoreAdapter +dev.caskeleton.adapter.outbound.persistence.operation.JpaDurableOperationStore dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity dev.caskeleton.adapter.outbound.persistence.outbox.h2.H2OutboxClaimRepository +dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper -dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig @@ -172,4 +172,4 @@ dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortMapper dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortRegistry dev.caskeleton.adapter.outbound.persistence.springdata.ScrollPolicy dev.caskeleton.adapter.outbound.persistence.transaction.CallerTransaction -dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort +dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction diff --git a/docs/architecture/persistence-fileserver-api-surface.txt b/docs/architecture/persistence-fileserver-api-surface.txt index bbb98130..893b0610 100644 --- a/docs/architecture/persistence-fileserver-api-surface.txt +++ b/docs/architecture/persistence-fileserver-api-surface.txt @@ -8,13 +8,13 @@ dev.caskeleton.adapter.outbound.persistence.fileserver.FileserverJpaPersistenceC dev.caskeleton.adapter.outbound.persistence.fileserver.FileserverSchemaActivation dev.caskeleton.adapter.outbound.persistence.fileserver.JpaCleanupQueue dev.caskeleton.adapter.outbound.persistence.fileserver.JpaContentReferenceLedger -dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadataStore -dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuotaService -dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaCommitGateway -dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaimGateway +dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata +dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileQuota +dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaCommit +dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaim dev.caskeleton.adapter.outbound.persistence.fileserver.JpaRecoveryQueue dev.caskeleton.adapter.outbound.persistence.fileserver.JpaStagingUploadLocator -dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSessionStore +dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession dev.caskeleton.adapter.outbound.persistence.fileserver.entity.CleanupItemEntity dev.caskeleton.adapter.outbound.persistence.fileserver.entity.FileEntity dev.caskeleton.adapter.outbound.persistence.fileserver.entity.QuotaReservationEntity diff --git a/docs/capability-status.md b/docs/capability-status.md index f9bd91f3..b3d08b87 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -508,3 +508,8 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap | web `MdcKeys` | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/MdcKeys.java` | `36ba0810` | shared-contract `observability.MdcKeys`로 이동(X2-P2-5) | | `DurableOperationJpaRepositoryShapeTest` | `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepositoryShapeTest.java` | `36ba0810` | `ScopedRowRepositoryShapeTest`로 흡수(테스트) | | notification `UuidV7Generator` 비트 배치 구현 | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java` | `36ba0810` | 클래스는 남기고 구현을 uuid-creator로 교체(S1-lead-2) | +| `poster.image-attached` v1 이벤트(`PosterEventPublisher.publishImageAttached`, `PosterImageAttached`, `PosterImageAttachedPayload`, `PortfolioEventContracts.POSTER_IMAGE_ATTACHED`, schema) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/{domain/poster/PosterImageAttached.java,application/event/PosterImageAttachedPayload.java}`, `src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/` | `36ba0810` | legacy 업로드 삭제 뒤 호출자 0(P24-new-2·P25-new-2) | +| fileserver inbound 서비스 인터페이스 6개(`UploadApplicationService`, `FinalizeUploadService`, `SingleShotUploadService`, `DownloadApplicationService`, `FileLifecycleService`, `FileserverAdminService`)와 구현 `DefaultUploadApplicationService`·`DefaultFinalizeUploadService`·`DefaultSingleShotUploadService`·`DefaultDownloadApplicationService`·`DefaultFileLifecycleService`·`DefaultFileserverAdminService`, `download/DownloadRequest` | `src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/{upload,download,lifecycle,admin}/` | `36ba0810` | 결정 32: 연산별 `port.in` use case로 대체(S1-#6b·S1-#18b) | +| `FileserverDownloadLifecycleConfiguration`, `FileserverMaintenanceServiceConfiguration`의 admin 서비스 bean | `src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/` | `36ba0810` | application use case 조립을 composition root(`composition:fileserver-platform`)로 | +| `FileserverUploadServiceConfiguration`(→ `FileserverUploadSupportConfiguration`로 개명, 서비스 bean은 use case 설정으로) | `src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/` | `36ba0810` | 같음 | +| `ca.auxiliary-source-set` 플러그인(`AuxiliarySourceSetPlugin`·`Extension`·`Spec`)과 `AuxiliarySourceSetConventionTest` | `src/build-logic/src/{main,test}/java/dev/caskeleton/buildlogic/auxiliary/` | `4f4bd1fd` | Gradle `jvm-test-suite`로 대체(BUILD-O3-5) | diff --git a/docs/fileserver/configuration.md b/docs/fileserver/configuration.md index f3f5bc9b..96fa86bd 100644 --- a/docs/fileserver/configuration.md +++ b/docs/fileserver/configuration.md @@ -45,6 +45,13 @@ Startup fails, rather than degrading, when any of these is missing or unsafe: | `write-roles` | `ROLE_FILE_WRITE` | grants create, append, finalize, delete, copy, move | | `admin-roles` | `ROLE_FILE_ADMIN` | grants reverify and force-delete, and gates `/internal/fileserver/**` at the servlet chain | +These roles decide the tier inside each operation. In front of it, every operation's use case +carries a `file:*` permission that the web adapter's method security checks against +`ca-skeleton.authz.role-permissions`; `security.yml` grants `file:read` to `ROLE_FILE_READ`, +`file:upload`, `file:delete`, `file:copy` and `file:move` to `ROLE_FILE_WRITE`, and `file:admin` to +`ROLE_FILE_ADMIN`. Renaming a tier role here means mapping the new name there as well, or the +caller is refused before the tier is consulted (`docs/fileserver/design-deviations.md` §5). + There is no anonymous-read switch. Every Fileserver route is authenticated by the servlet chain before any application policy is consulted, so such a setting could only ever have described a permission the transport had already refused — a configuration that reads as if it grants access diff --git a/docs/fileserver/design-deviations.md b/docs/fileserver/design-deviations.md index a7fd742e..17124522 100644 --- a/docs/fileserver/design-deviations.md +++ b/docs/fileserver/design-deviations.md @@ -12,7 +12,7 @@ A create that fails after the record exists must end in `FAILED`, but the table The record therefore walks `CREATED → UPLOADING → FAILED`, which is also the honest reading: the upload had been admitted before it failed. -Pinned by `UploadApplicationServiceTest` (application-core). +Pinned by `ResumableUploadUseCasesTest` (application-fileserver). ### 2. `ContentKey`'s alphabet admits a leading separator @@ -28,7 +28,7 @@ Deleting a file that is mid-verification has no legal transition. The lifecycle with `409 FILE_NOT_READY` rather than inventing an edge, which matches the allowed-state list the JPA `markDeleting` statement already enforced. -Pinned by `FileLifecycleServiceTest`. +Pinned by `FileLifecycleUseCasesTest`. ### 4. `If-Match` is specified as an ETag but the lifecycle was designed around the row version @@ -36,7 +36,7 @@ The HTTP contract sends an entity tag; the metadata store guards on a numeric ve takes `Optional expectedEtag` and compares against the record's strong validator, so the precondition a client sends is the precondition that is checked. -Pinned by `FileLifecycleServiceTest`. +Pinned by `FileLifecycleUseCasesTest`. ### 5. The filename policy left `:` intact @@ -174,40 +174,44 @@ an extension point for a backend this template does not ship: `ContentStoreCapabilities` reports what the running store actually supports, so no unimplemented SPI is advertised as available. -## Known deviation from the repository's application-layer contract +## The repository's application-layer contract -### 5. Fileserver application services are not `CommandUseCase` / `QueryUseCase` +### 5. Fileserver operations are use cases (resolved, owner decision 32) -`src/application-core/CLAUDE.md` requires every inbound port implementation to extend -`CommandUseCase` or `QueryUseCase` and to carry `@UseCaseCapability`, which declares its transaction -mode, idempotency and repository access. The Fileserver instead exposes multi-method services — -`UploadApplicationService`, `DownloadApplicationService`, `FileLifecycleService`, -`FileserverAdminService` and their `Default*` implementations. +Every operation the transport reaches is a `CommandUseCase` or `QueryUseCase` behind a one-method +port in `application.fileserver.port.in` — create, append, status, cancel, finalize and the +single-request upload; describe, prepare, open and transfer for downloads; delete, copy and move; +and the eight management-plane operations. Each implementation (`*ApplicationUseCase`) declares its +`@UseCaseCapability`, so the ArchUnit rules that check transaction mode, repository access and +outbound calls now see the Fileserver like every other feature. -This is a real deviation, not an oversight, and it is unenforced: the ArchUnit rules -`inbound_port_implementations_end_with_use_case` and -`inbound_port_implementations_declare_capability` only match types that implement `UseCase`, so a -service that never does is silently exempt. The capability contract that every other feature in -this repository declares is therefore absent here. +Two authorities guard a write, and both stay: -Two things follow from it. The transaction mode of each operation is expressed only by which -`TransactionPort` method the body happens to call, rather than declared and checked. And the -application layer holds transport policy it would not hold if each operation were a use case with -its own command: HTTP status codes on `FileserverErrorCode`, `Range` and conditional-request -parsing in `api.transfer`, and `Content-Disposition` construction. +| Check | Where | Decides | +| --- | --- | --- | +| `@RequiresPermission("file:…")` | the use case's proxy, enforced by the web adapter's method security | whether the caller's roles grant the operation at all | +| `FileAccessPolicyPort` | inside the use case, before any side effect | the tier (read/write/admin), and that the caller owns the file in its tenant | -The status mapping in particular is a deliberate trade rather than an accident. It lives in -`application-core` so the servlet transport, the reactive transport and the Nginx delegation path -cannot answer the same failure with three different statuses. Moving it to the transport layer -resolves the layering complaint and reintroduces exactly that drift, which is why this is an -architecture decision rather than a cleanup. +The permissions are `file:read` (describe, download, upload status), `file:upload` (create, +append, finalize, cancel, the single-request upload), `file:delete`, `file:copy`, `file:move` and +`file:admin` (every management-plane operation). `security.yml` grants them to `ROLE_FILE_READ`, +`ROLE_FILE_WRITE` and `ROLE_FILE_ADMIN` — the fileserver's own default tier roles — so a caller +holding a tier holds its permissions. A deployment that renames the tier roles, or supplies its own +`FileAccessPolicyPort` under other role names, maps those names in +`ca-skeleton.authz.role-permissions` too; `security.access-policy: unenforced` relaxes only the +tier and ownership check, never the permission gate. -**Status: open, deliberately unresolved in this change set.** Closing it means roughly thirty -command/query use cases, a decision about where the shared status vocabulary lives, and a change to -the ArchUnit rules so a service that bypasses the contract fails the build instead of being exempt -from it. That belongs in its own ADR with its own review, and doing it inside a correctness patch -would mix a large mechanical refactor into changes that need to be readable. +The resumable transfers run on the transfer pool, and method security reads the security context +of the calling thread, so `BlockingTransferExecutor` carries the request's context onto the worker +(`BlockingTransferExecutorSecurityContextTest`). Without it an authenticated append was refused as +anonymous. -Nothing here is pinned by a test, because the deviation is the absence of a constraint. The next -step is the ADR, not another test. +What is not a use case is what no transport calls: `CleanupService` and +`FileReconciliationService` are driven by background workers with no caller identity, and a +mutating use case must declare a permission a scheduler could not hold. +`FileserverUseCaseContractDeviationTest` freezes that list. + +The HTTP status vocabulary on `FileserverErrorCode` stays in the application layer, for the reason +this section used to give: the servlet transport and the Nginx delegation path must not answer the +same failure with different statuses. diff --git a/docs/jpa/observability.md b/docs/jpa/observability.md index 660bfb67..ad05f819 100644 --- a/docs/jpa/observability.md +++ b/docs/jpa/observability.md @@ -5,7 +5,7 @@ Design §37. What is measured, and what must never appear in a measurement. ## What is emitted by default Nothing JPA-specific. No composition constructs a `MeterRegistry`-backed observation for the -platform, and `SpringTransactionPort` records no transaction metric. The `jpa.transaction.*` meters +platform, and `SpringTransaction` records no transaction metric. The `jpa.transaction.*` meters this page used to list (`duration`, `rollback`, `timeout`, `completion.unknown`) were produced by `JpaTransactionObservation`, which nothing constructed; it was removed on 2026-09-25 (`docs/capability-status.md`). Transaction outcomes are visible through the shared persistence error diff --git a/docs/jpa/runbooks.md b/docs/jpa/runbooks.md index d4598b11..ad14f251 100644 --- a/docs/jpa/runbooks.md +++ b/docs/jpa/runbooks.md @@ -27,7 +27,7 @@ reason. **Signal:** `DB_DEADLOCK` / serialization failures rising in the persistence error codes. -`SpringTransactionPort` does not retry, so each one reaches the caller. +`SpringTransaction` does not retry, so each one reaches the caller. 1. Group the failures by operation. A single operation dominating means a hot row or an inconsistent lock order. diff --git a/docs/jpa/transaction-guide.md b/docs/jpa/transaction-guide.md index 2c1802ab..2b7d6f71 100644 --- a/docs/jpa/transaction-guide.md +++ b/docs/jpa/transaction-guide.md @@ -6,7 +6,7 @@ Design §15-§20. What owns a transaction, what may be retried, and what must ne Repository adapters do not open transactions. The use case does, through `TransactionPort`, because the unit of work is a business decision and only the use case knows where it starts and -ends. `SpringTransactionPort` is the only implementation: one pre-built `TransactionTemplate` per +ends. `SpringTransaction` is the only implementation: one pre-built `TransactionTemplate` per mode over Spring's `PlatformTransactionManager`, every mode pinned to `READ_COMMITTED`. | Call | Propagation | When | @@ -28,7 +28,7 @@ maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1 ## Nothing is retried by the port -`SpringTransactionPort` runs the action once. A failure rolls back and propagates, translated to +`SpringTransaction` runs the action once. A failure rolls back and propagates, translated to the shared persistence error codes where the SQLSTATE is known. A caller that decides to retry must re-run the whole use case in a new transaction — never re-issue one statement — because an optimistic conflict or a serialization failure means the state the attempt computed against is no diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P28.md b/docs/reviews/2026-09-25-review-followup-results/W3-P28.md new file mode 100644 index 00000000..270abd39 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P28.md @@ -0,0 +1,25 @@ +## 행 결과 +| ID | 결과 | 근거 | +|---|---|---| +| S1-#6b | 완료 | P28 W3 `b06b4166`(결정 32). transport가 부르는 21개 연산을 `application-fileserver/.../port/in/*UseCase`(연산 하나씩, `CommandUseCase`/`QueryUseCase`) + `*Command`/`*Query`로 선언하고 구현 `*ApplicationUseCase`(upload·download·lifecycle·admin 패키지)에 `@UseCaseCapability`를 단다. 권한: `file:read`(describe·prepare·open·transfer·upload status), `file:upload`(create·append·finalize·cancel·single-request upload), `file:delete`, `file:copy`, `file:move`, `file:admin`(관리 plane 8개). `FileAccessPolicyPort`(tier·소유자·tenant)는 각 use case 안에서 그대로(결정 32 "둘 다"). `security.yml` `"[ROLE_FILE_READ]": file:read`, `"[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move`, `"[ROLE_FILE_ADMIN]": file:admin`(fileserver 기본 tier 역할 이름을 key로 — 한 역할이 권한과 tier를 함께 준다), dev Keycloak realm에 같은 client role 3개(`ROLE_FILE_ADMIN`은 서비스 계정에 미부여), `docs/fileserver/design-deviations.md` §5·`configuration.md`·`infra/keycloak/README.md`. 조립은 `composition:fileserver-platform`의 `FileserverUploadUseCaseConfiguration`·`FileserverFileUseCaseConfiguration`·`FileserverAdminReadUseCaseConfiguration`·`FileserverAdminActionUseCaseConfiguration`(BOOT-007 8-bean 한도), adapter의 download/lifecycle/admin 서비스 조립 삭제. 테스트: `FileserverCompositionIntegrationTest.anUploadByATierWithoutTheUploadPermissionIsRefusedBeforeAnythingIsStaged`(실제 PG, `MethodSecurityConfig` 없이 FAIL 1건 → 포함 PASS; fileserver tier는 통과하지만 권한 매핑이 없는 역할 `ROLE_UNMAPPED_WRITER`), 같은 클래스 3건 PASS; `BlockingTransferExecutorSecurityContextTest.workOnTheTransferPoolSeesTheCallersAuthentication` FAIL(assertion) → PASS(전송 풀 작업에 요청 SecurityContext 전달 — 없으면 append·finalize·download stream이 권한 게이트에서 익명으로 거부됨). ArchUnit: fileserver access policy 패키지(`adapter.outbound.fileserver.platform.security`, IO 없음)를 D7 in-process driven outbound로 추가(`ApplicationBoundaryArchitectureTest.isInProcessDrivenOutbound`), `FileserverUseCaseContractDeviationTest` 동결 목록을 `DefaultCleanupService`·`DefaultFileReconciliationService`·`WriterLeaseCoordinator`로 축소(배경 작업은 caller identity가 없어 권한을 가질 수 없음). `:app-bootstrap:architectureTest` PASS. 수정 방향과 다른 점: 트랜잭션을 열지 않던 append·status·download read·incomplete-list는 `USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY` 때문에 해당 경계(`inWrite`로 lease commit 감쌈 — coordinator 경계에 join, `inRead`로 조회)를 직접 연다; 여러 use case를 합성하는 single-request upload·operator cleanup은 `RepositoryAccess.NONE`(각 단계가 자기 경계를 연다) | +| S1-#18b | 완료 | P28 W3 `b06b4166`: inbound `UploadApplicationService`·`DownloadApplicationService`·`FileLifecycleService`·`FileserverAdminService`·`SingleShotUploadService`·`FinalizeUploadService`와 `Default*` 구현을 `port.in/*UseCase` + `*ApplicationUseCase`로(notification의 `port.in` 규칙과 같음). 남긴 `*Service`는 transport가 부르지 않는 배경 작업 `CleanupService`·`FileReconciliationService`뿐 — 쓰기 use case는 `@RequiresPermission`이 필수인데 scheduler는 권한을 가질 caller가 없으므로 use case로 만들면 매 실행이 거부된다(`FileserverUseCaseContractDeviationTest` 주석) | +| S4-lead-2 | 남음 | 한 것(P28 W3 `da49df6c`): fileserver의 descriptor 기반 primitive를 `adapter/outbound/support/.../support/filesystem/SecureDirectoryWalk.java`(이동, public)·`SecureFileAccess.java`(신규: createNew·openForRead/Write·deleteRegularFile·readAttributes·isRegularFile·createParentDirectories)로 올리고, 거부를 에러 코드 없는 타입 있는 `IOException`(`SymbolicComponentException`·`PathEscapeException`·`NotRegularFileException`)으로. fileserver `SafeFileChannelFactory`는 위임 + `LocalStorageFailures` 번역만(P24 메모대로 번역 분리). 테스트: `SecureFileAccessTest` 8건(symlink leaf·symlink 디렉터리 component·`..` 탈출·create-only 충돌·symlink delete 거부·열린 뒤 디렉터리를 link로 바꾸는 race `aDirectorySwappedForALinkAfterItWasOpenedDoesNotRedirectTheOperation`), `SecureDirectoryWalkTest` 2건(support로 이동), `LocalStorageFailuresTest` 2건 FAIL→PASS(P28-new-1). fileserver·support `check`, PG lane `postgresqlFileserver{Migration,Metadata,Reclamation}IntegrationTest` 6·15·15 PASS. 남은 것: objectstorage `LocalObjectPathGuard`를 이 primitive로 바꾸는 재작성(과 objectstorage→support registry edge). 이유: local-dev provider의 쓰기는 "없거나 완전한" 게시를 위해 임시 파일을 `Files.createLink`(link(2))로 create-only 연결하는데, `SecureDirectoryStream`에는 linkat이 없고 `move`는 기존 대상을 덮어쓴다(renameat2 NOREPLACE 미노출). descriptor 기반으로 바꾸면 create-only 원자 게시를 잃거나(대상 선점 후 덮어쓰기 — 읽는 쪽이 빈/부분 객체를 볼 수 있음) native 호출이 필요해 설계 결정이 먼저다. 읽기·retire 경로만 바꾸면 쓰기 경로의 race가 남아 "한 primitive"가 되지 않으므로 이번 묶음에서는 손대지 않음(대상은 local-dev 전용 provider) | +| S6-#10a | 남음 | / P28 에이전트가 세션 재시작으로 중단(미커밋) — P30으로 | +| S2-#8a | 남음 | 한 것(P28 W3 `537310f9`): persistence-fileserver의 `@ComponentScan` + store 9개 클래스별 `@Repository`·`@ConditionalOnProperty`를 없애고, 조건 한 곳(`FileserverJpaPersistenceConfig`, 이 leaf의 `AutoConfiguration.imports` root) + 명시적 `@Bean` 설정 둘(`FileserverJpaMetadataStoreConfig`·`FileserverJpaQueueStoreConfig`)을 `@Import` — notification(`NotificationJpaPersistenceFacade`)과 같은 방식. web-fileserver 컨트롤러 4개·예외 처리기가 조립 root가 이미 거는 `app.fileserver-platform.enabled`를 반복하던 것 삭제(tus·draft12·admin은 자기 스위치만). 검증: persistence-fileserver·web-fileserver·composition fileserver `check`, PG lane `postgresqlFileserver{Metadata,Reclamation}IntegrationTest` 15·15, `FileserverCompositionIntegrationTest` 3 PASS. 남은 것: persistence-jpa `JpaAdapterComponentsConfig`의 8개 패키지 stereotype 스캔. 이유: 스캔이 있는 까닭이 이 leaf의 패키지 경계 목록(`JpaModuleBoundaryTest.PACKAGE_CATALOG`)이 `config`/`autoconfigure` → `audit`·`failure`·`liveevent`·`lock`·`operation`·`outbox` edge를 허용하지 않기 때문이다 — 명시적 `@Bean`으로 바꾸려면 (a) `autoconfigure`에 6개 edge를 추가하거나 (b) 패키지마다 capability 스위치를 반복하는 auto-configuration을 두어야 해서 leaf 내부 모듈 지도 결정이 먼저다(`JpaAdapterComponentsConfigTest`·`PersistenceEntityScanCoverageTest`가 스캔 계약을 고정). Mongo는 이미 자기 `AutoConfiguration.imports` 둘 + `@Bean` 방식이라 변경 없음(남은 것은 `MongoPlatformAutoConfiguration`의 bean별 조건 반복 19개) | +| S2-#13b | 완료 | P28 W3 `2619cb18`: 규칙 `<포트 이름에서 Port를 뺀 것>` 하나로 24개 개명(테스트 클래스 이름 포함). persistence-fileserver `JpaFileMetadata`·`JpaFileQuota`·`JpaQuotaCommit`·`JpaQuotaReclaim`·`JpaUploadSession`(이미 규칙대로인 `JpaCleanupQueue`·`JpaContentReferenceLedger`·`JpaRecoveryQueue`·`JpaStagingUploadLocator`는 유지); fileserver adapter `LocalCleanupContent`·`LocalCopyContent`·`LocalOrphanScan`·`LocalReconciliationContent`·`LocalStorageHealth`·`LocalStorageUsage`·`LocalUploadContent`·`LocalUploadStorage`·`StructuredAdminAudit`·`StructuredFileserverAudit`·`RandomUploadIdentifier`; persistence-jpa core `SpringTransaction`·`JpaOutboxStore`·`JpaDurableOperationStore`·`PostgreSqlIdempotencyStore`·`LockRegistryDistributedLock`·`MeteredDistributedLock`·`DomainContextAuditContext`·`JpaLiveEventReplay`. 행에 적힌 `CanonicalOutboxAppendAdapter`는 P18에서 이미 삭제됨. 유지(이유): `LocalBlockingContentStore`(포트 3개를 구현하는 store 자체), `VerificationCoordinator`(verifier 파이프라인 합성 — 기술 어댑터가 아님), `RoleBased`/`UnenforcedFileAccessPolicy`(이미 `<정책>`). 문서·README·CLAUDE.md의 단순 이름과 PG 통합 테스트의 bean 이름 문자열도 갱신. API surface 재승인(`updateJpaApiSurface -PapproveJpaApiSurfaceChange`, `updatePersistenceFileserverApiSurface -PapprovePersistenceFileserverApiSurfaceChange`, 개수 증가 없음). persistence-jpa·persistence-fileserver·fileserver·composition fileserver·idempotency·application-core·notification·persistence-notification `check`, `:app-bootstrap:architectureTest`·`test` PASS | +| P24-new-2 | 해당 없음(코드 삭제) | P28 D `a49342e2`: `PosterEventPublisher.publishImageAttached`, `domain/poster/PosterImageAttached`, `PosterImageAttachedPayload`, `PortfolioEventContracts.POSTER_IMAGE_ATTACHED`와 그 bean, `contracts/messaging/poster.image-attached/v1.schema.json` 삭제. `git grep "ImageAttached\b"` 0건. `:sample-portfolio:test` PASS | +| P25-new-2 | 해당 없음(코드 삭제) | P24-new-2와 같음(`a49342e2`) | +| P24-new-3 | 완료 | P28 W3 `12f0b183`: `FileVerifier`를 `application-fileserver/.../api/security`에서 `adapter/outbound/fileserver/.../platform/verification/FileVerifier.java`로 이동(사용처는 그 패키지의 verifier 5개·`VerificationCoordinator`·`FileserverVerificationConfiguration`뿐). application은 `FileVerificationPort`만 본다 | +| P23-new-1 | 완료 | P28 W2 `b13cf08b`: `AppliedMigrationImmutabilityTest.MIGRATION_ROOTS`에 `../persistence-fileserver/src/main/resources/db/migration` 추가 → `everyVersionedMigrationIsPinned` FAIL(`AssertionError at AppliedMigrationImmutabilityTest.java:72`, `jpa/fileserver/V1..V5` 미고정) → `applied-migrations.sha256`에 5줄 추가 후 PASS. `persistence-jpa/build.gradle` test `inputs.dir(...fileserver migration)` 추가. 새 migration 버전은 추가하지 않음 | +| P23-new-2 | 완료 | P28 W2 `b13cf08b`: `ProviderRuntimeRegistryTest.closingTheRegistryClosesTheAdapterOfEveryRegisteredGeneration` FAIL(컴파일 실패 `cannot find symbol registry.close()`) → PASS; `SesNotificationProviderAdapterTest.closingTheAdapterClosesItsSdkClient` PASS. `SesNotificationProviderAdapter implements AutoCloseable`(`close()`→`client.close()`), `ProviderRuntime.release()`, `ProviderRuntimeRegistry implements AutoCloseable`(현재·drain 세대 모두 release) — `providerRuntimeRegistry` `@Bean`의 추론 destroy method로 context 종료 때 호출. `:adapter:outbound:notification:check` PASS | + +## 제거된 코드 +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +|---|---|---|---| +| `poster.image-attached` v1 이벤트(`PosterEventPublisher.publishImageAttached`, `PosterImageAttached`, `PosterImageAttachedPayload`, `PortfolioEventContracts.POSTER_IMAGE_ATTACHED`, schema) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/{domain/poster/PosterImageAttached.java,application/event/PosterImageAttachedPayload.java}`, `src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/` | `36ba0810` | legacy 업로드 삭제 뒤 호출자 0(P24-new-2·P25-new-2) | +| fileserver inbound 서비스 인터페이스 6개(`UploadApplicationService`, `FinalizeUploadService`, `SingleShotUploadService`, `DownloadApplicationService`, `FileLifecycleService`, `FileserverAdminService`)와 구현 `DefaultUploadApplicationService`·`DefaultFinalizeUploadService`·`DefaultSingleShotUploadService`·`DefaultDownloadApplicationService`·`DefaultFileLifecycleService`·`DefaultFileserverAdminService`, `download/DownloadRequest` | `src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/{upload,download,lifecycle,admin}/` | `36ba0810` | 결정 32: 연산별 `port.in` use case로 대체(S1-#6b·S1-#18b) | +| `FileserverDownloadLifecycleConfiguration`, `FileserverMaintenanceServiceConfiguration`의 admin 서비스 bean | `src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/` | `36ba0810` | application use case 조립을 composition root(`composition:fileserver-platform`)로 | +| `FileserverUploadServiceConfiguration`(→ `FileserverUploadSupportConfiguration`로 개명, 서비스 bean은 use case 설정으로) | `src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/` | `36ba0810` | 같음 | + +## 새로 발견한 결함 +- `P28-new-1` (고침, `da49df6c`): `adapter/outbound/fileserver/.../platform/local/AtomicMoveContentPublisher.java`(`SecureDirectoryWalk.move`)와 `ContentPublishVerification.java`(`SecureDirectoryWalk.inDirectory`)는 walk를 직접 불러 거부를 `LocalStorageFailures.translate`로 번역했는데, 거기서는 `SymbolicComponentException`·경로 탈출이 일반 `IOException`으로 분류돼 `STORAGE_UNAVAILABLE`(재시도 가능 503)이 됐다 — 클라이언트가 이미 link로 바뀐 경로로 재시도한다. `SafeFileChannelFactory`만 symlink를 따로 잡고 있었다. `LocalStorageFailures.translate`가 walk의 타입 있는 거부를 모두 `PATH_OUTSIDE_NAMESPACE`(재시도 불가)로. `LocalStorageFailuresTest.aSymbolicComponentRefusedByTheWalkIsAPermanentPathRejection`·`aTargetOutsideTheRootIsAPermanentPathRejection` FAIL(분기 제거 시 2건 실패) → PASS. (커밋 라벨은 W3지만 이 결함 수정이 함께 들어 있다.) diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P29.md b/docs/reviews/2026-09-25-review-followup-results/W3-P29.md new file mode 100644 index 00000000..2a24b016 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P29.md @@ -0,0 +1,18 @@ +# W3-P29 결과 (에이전트 중단 후 오케스트레이터가 통합 검증으로 확정) + +worktree: `.claude/worktrees/agent-aa7d1d4704847ed1c` (브랜치 `worktree-agent-aa7d1d4704847ed1c`) +커밋: `e3a0bd32` (jvm-test-suite), `3967c9ef` (redis-sdk api) + +## 행 결과 +| ID | 결과 | 근거 | +|---|---|---| +| BUILD-O3-5 | 완료 | `e3a0bd32`. `ca.auxiliary-source-set` 삭제, 13 leaf → `testing.suites`. TDD: `StrictTestLaneConventionTest.aLaneNamedAfterItsJvmTestSuiteMakesTheSuiteTaskStrict` FAIL(이전 플러그인: "Cannot add task 'integrationTest' as a task with that name already exists.") → PASS / 통합 검증(2026-09-29): ci·mainCheck·build-logic test·optional-platforms ci·releaseCheck 통과, integrationCheck는 jar 리소스 목록 조회 1건 수정 후 재실행 | +| BUILD-결론-1 | 완료 | build-logic Java 6,068 → 5,851줄(main 3,966 + test 1,885) / 수정 방향(O3-2·5·6) 전부 이행: 16,768 → 5,851줄(main 3,966 + test 1,885). main+test 합계는 목표 3.5–4k 초과 — 남은 것은 아키텍처 코어·컨벤션·레인 하나와 그 테스트 | +| P22-new-3 | 완료 | `3967c9ef`. redis-sdk만 `java-library` + `api project(':adapter:outbound:redis-runtime')` / 통합 검증 통과(redis-sdk java-library + api redis-runtime) | + +## 제거된 코드 +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +|---|---|---|---| +| `ca.auxiliary-source-set` 플러그인(`AuxiliarySourceSetPlugin`·`Extension`·`Spec`)과 `AuxiliarySourceSetConventionTest` | `src/build-logic/src/{main,test}/java/dev/caskeleton/buildlogic/auxiliary/` | `4f4bd1fd` | Gradle `jvm-test-suite`로 대체(BUILD-O3-5) | + +## 새로 발견한 결함 diff --git a/docs/reviews/2026-09-25-review-followup-status.md b/docs/reviews/2026-09-25-review-followup-status.md index 4d06c60e..5d65e54e 100644 --- a/docs/reviews/2026-09-25-review-followup-status.md +++ b/docs/reviews/2026-09-25-review-followup-status.md @@ -583,7 +583,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | ID | 심각도 | 요약 | 상태 | 근거 | Wave | 수정 방향 | |---|---|---|---|---|---|---| -| BUILD-결론-1 | 권고 | 빌드 코드가 목적에 비해 너무 큼(16,768줄 중 아키텍처 검사 13%) | 남음 | 현재 Java(main+test) build-logic 6,184 + build-tools 4,320 = 10,504줄. O3 목표는 3.5–4k줄
Wave 3 W3-P16: 미완 — build-logic+build-tools Java 10,504줄 → build-logic 6,185줄(main 4,184 + test 2,001; build-tools 0). 목표 3.5–4k에는 BUILD-O3-5 나머지(auxiliary → jvm-test-suite, release-provenance 제거)가 필요
Wave 3 W3-P27: 미완 — O3-5 나머지 뒤 build-logic Java 줄 수로 판정 | W3 | BUILD-O3-2·5·6 진행으로 줄인다 | +| BUILD-결론-1 | 권고 | 빌드 코드가 목적에 비해 너무 큼(16,768줄 중 아키텍처 검사 13%) | 완료 | Wave 3 W3-P29 (Wave 3 라운드 3 커밋): build-logic Java 6,068 → 5,851줄(main 3,966 + test 1,885) / 수정 방향(O3-2·5·6) 전부 이행: 16,768 → 5,851줄(main 3,966 + test 1,885). main+test 합계는 목표 3.5–4k 초과 — 남은 것은 아키텍처 코어·컨벤션·레인 하나와 그 테스트 | - | BUILD-O3-2·5·6 진행으로 줄인다 | | BUILD-결론-2 | 권고 | 기능별 증거 검사(E)가 46%로 가장 큰 덩어리 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): 기능별 evidence 검사 중 JPA(`jpa/` 2,701+706줄, `junit/` 138+76줄) 삭제. 남은 E는 redis topology(소유자 결정 4로 유지) | - | JPA evidence 폐기(BUILD-O3-2) | | BUILD-결론-3 | 권고 | 아키텍처 게이트(방향 task·ArchUnit)는 크기가 적정하니 유지 | 완료 | `src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java:58-223` 방향·순수성·ignored-source 유지, `src/app-bootstrap/build.gradle:45-52` architectureTest 레인 유지 | - | - | | BUILD-결론-4 | 권고 | 09-16 단계 분리 계획이 절반만 이행됨(2단계 게이트가 PR에서 돎) | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): 하위 행으로 추적: B2·B4-17·B4-27·B4-28·B4-30·중복-6 완료, B3의 "변경 모듈만 실행"과 C는 보류(각 행) | - | 해당 행 참고 | @@ -613,7 +613,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | BUILD-O3-2 | 권고 | O3: JPA evidence manifest(`ca.jpa-evidence`, `ca.jpa-qualification`) 폐기, leaf 테스트로 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): build-tools `jpa/`·`junit/`, `ca.jpa-evidence`·`ca.jpa-qualification` 삭제. readiness 카드 검사 → `JpaReadinessRegistryTest`(persistence-jpa `test`, 입력 `readiness-cards.yaml`·`src/postgresqlIntegrationTest/java` 선언). `everyImplementedCardNamesTasksThisLeafDeclares` FAIL(삭제된 `verifyJpaPrimaryFoundationEvidence`를 가리키던 카드, AssertionError at :106) → 카드를 `integrationTestLaneCheck`로 고쳐 PASS. 카드가 인용한 scenario는 readiness 레인의 `requires` + `rejectSkipped`로(manifest가 JUnit XML로 확인하던 것). `jpaReleaseQualification`은 leaf 집계 태스크(registry의 blocking gate를 dependsOn). workflow: `jpa-r2-evidence.yml`, integration-main `jpa-candidate-evidence` 삭제 | - | 두 플러그인과 `junit` 패키지를 삭제하고, readiness/release registry 검사만 persistence-jpa 테스트(inputs 선언)로 옮김. workflow의 evidence task 호출도 정리 | | BUILD-O3-3 | 권고 | O3: verifyEnvKeys 위치 | 완료 | 소유자 결정은 bootstrap에 유지. 현재 `src/app-bootstrap/build.gradle:5`(`ca.config-contract`), `src/build.gradle:75-79`→mainCheck | - | - | | BUILD-O3-4 | 권고 | O3: redis topology lane을 strict lane으로 흡수 | 완료 | 소유자 결정은 유지. `src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/` 유지, `.github/workflows/redis-sdk-topology.yml` 경로 필터 PR | - | - | -| BUILD-O3-5 | 권고 | O3: build-logic에는 코어·컨벤션·레인 하나만 남김(인벤토리 #11·#18·#19·#20·#31) | 남음 | 남은 비핵심 플러그인(main+test 줄 수): publicpath 288+37, archive 216+46, release 138+71, bootstrap(developer-bootstrap·bootrun-dotenv) 328+203, auxiliary 151+145. leaf 버전은 아직 SHA 버전(`src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java:36-39`)
Wave 3 W3-P16: 미완 — 완료: public-path → app-bootstrap `PublicPathSnapshotTest`(main 단계 레인 `publicPathSnapshotTest`, 루트 별칭 `verifyPublicPathSnapshot`, 승인 `-PapprovePublicPathChange`; 기준선은 헤더의 명령만 바뀜), developer-bootstrap → `scripts/bootstrap-local.sh`, leaf version에서 revision 제거 후 archive-hygiene 삭제, app-bootstrap `springBoot.buildInfo`(`build.revision`, `time` 제외). 남음: (1) `ca.release-provenance` 플러그인 제거 — `src/optional-platforms/build.gradle`이 적용하고 있어 이번 Wave에서 건드리지 않기로 한 gRPC build 파일 수정이 필요, (2) auxiliary → `jvm-test-suite` — grpc·messaging 포함 14개 leaf build 파일을 바꾸는 작업이라 동시 묶음과 충돌. 둘 다 다음 순차 작업으로
Wave 3 W3-P27: 미완 — 완료분: `302ba915` `ca.release-provenance` 제거(leaf version·sourceRevision은 `ca.java-conventions`의 `JavaConventionsPlugin.sourceRevision`, 루트 `verifyReleaseProvenance`는 같은 함수를 부르는 build.gradle 태스크, TestKit 테스트는 `PlatformModuleConventionTest`로). 남은 것: auxiliary 레인 → `jvm-test-suite`(중단된 WIP 패치) | W3 | public-path는 app-bootstrap approval test로, release-provenance는 `springBoot { buildInfo() }`로 바꾸고, leaf 버전 고정 후 archive-hygiene 삭제. developer-bootstrap은 `scripts/`로, auxiliary는 `jvm-test-suite`로 | +| BUILD-O3-5 | 권고 | O3: build-logic에는 코어·컨벤션·레인 하나만 남김(인벤토리 #11·#18·#19·#20·#31) | 완료 | Wave 3 W3-P29 (Wave 3 라운드 3 커밋): `e3a0bd32`. `ca.auxiliary-source-set` 삭제, 13 leaf → `testing.suites`. TDD: `StrictTestLaneConventionTest.aLaneNamedAfterItsJvmTestSuiteMakesTheSuiteTaskStrict` FAIL(이전 플러그인: "Cannot add task 'integrationTest' as a task with that name already exists.") → PASS / 통합 검증(2026-09-29): ci·mainCheck·build-logic test·optional-platforms ci·releaseCheck 통과, integrationCheck는 jar 리소스 목록 조회 1건 수정 후 재실행 | - | public-path는 app-bootstrap approval test로, release-provenance는 `springBoot { buildInfo() }`로 바꾸고, leaf 버전 고정 후 archive-hygiene 삭제. developer-bootstrap은 `scripts/`로, auxiliary는 `jvm-test-suite`로 | | BUILD-O3-6 | 권고 | O3: build-tools를 비움 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): `config` 패키지를 `dev.caskeleton.buildlogic.config`로 이동(테스트 2개 포함), `includeBuild('build-tools')`·Dockerfile `COPY build-tools/`·build-logic.yml step 삭제, `src/build-tools` 삭제. 태스크는 `:app-bootstrap:verifyEnvKeys` 그대로(PASS) | - | JPA 폐기 후 `ConfigContractPlugin`을 build-logic으로 옮기고 `includeBuild('build-tools')` 삭제. task는 계속 `:app-bootstrap:verifyEnvKeys` | | BUILD-바로할것-1b | Nit | runtime-membership 삭제 후 남은 주석 문구 | 남음 | `src/sample-portfolio/build.gradle:175`, `.github/workflows/ci-quality-gates.yml:55` "runtime-membership policy" | W5 | 두 주석에서 해당 문구 삭제 | | BUILD-바로할것-4 | 권고 | `ca.strict-qualification`을 `strictTestLanes` requires + rejectSkipped로 (= O-8) | 완료 | `strictQualification` grep 0건, id 없음. 예: `src/app-bootstrap/build.gradle:61-68` 레인 `requires`+`rejectSkipped` | - | - | @@ -783,7 +783,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#4 | Required | `NotificationDispatchService` 생성자 15개, record 필드별 재조립·실패 분류가 한 클래스에 (B-5 구조 원인) | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 구조 변경(결함 아님, 기존 동작 테스트로 회귀 확인). record 재조립 4곳을 전이 메서드로: `application-notification/.../dispatch/DeliveryAttemptRecord.java:97`(`completed`)·`:135`(`closedBeforeSubmission`), `RecipientDeliveryRecord.java:73`(`advancedRoute`)·`:113`(`failedBeforeAttempt`)·`:156`(`afterAttempt`)·`:194`(`terminalStateFor`, 종료 상태 계산 1곳). catch 3분기는 `ProviderOutcomeClassifier.java:31`(`fromException`), 호출은 `NotificationDispatchService.java:332`. `DispatchOutcomeRecorder`는 `attempt.completed`·`current.afterAttempt` 두 줄. 새 테스트 `ProviderOutcomeClassifierTest`(3건) PASS, `NotificationDispatchServiceTest`·`DispatchOutcomeRecorderTest` 그대로 PASS. 남은 점: 생성자 인자는 여전히 15개(`NotificationDispatchService.java:82`, registry→renderer로 바뀐 것뿐). 인자는 모두 실제 포트·정책이라 수정 방향에 없는 묶음 record를 새로 만들지 않았다 | - | `DeliveryAttemptRecord.completed(result, at)`·`RecipientDeliveryRecord.advancedRoute(now)` 전이 메서드 추가, catch 분기는 `ProviderOutcomeClassifier` 정적 메서드로 분리 | | S1-#5 | Required | fileserver retire 절차 3곳 복사, admin `forceDelete`는 content 없는 레코드를 DELETING에 남김 (C-4 관련) | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): `FileserverAdminServiceTest.forceDeletingAFileThatWasNeverPublishedRetiresItCompletely` FAIL(`expected: DELETED but was: DELETING`)→PASS. 세 호출부가 `src/application-fileserver/.../cleanup/FileRetirement.java:40` 하나를 쓴다: `DefaultFileLifecycleService.java:84`, `DefaultFileserverAdminService.java:167`, `DefaultUploadApplicationService.java:265`. `cleanup` 패키지에 둔 이유: 세 호출 패키지가 이미 cleanup을 의존하고 cleanup은 그들을 의존하지 않아 새 패키지 순환이 생기지 않는다 | - | `retire(FileRecord)` 하나로 합치고 content 없으면 DELETING→DELETED 전이를 세 호출부 모두에 적용 | | S1-#6a | Required | fileserver 단일 구현 인터페이스 6개(fake 없음) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `1ec8f087`·`8e731b9f`. 구현 1개·대역 0인 `WriterLeaseCoordinator`·`TransferAdmissionController` 인터페이스를 지우고 `Default*`가 그 이름을 가짐, `FileStateMachine`은 S1-#13으로 삭제. 수정 방향과 다르게 남긴 3개와 이유: `FileLifecycleService`는 web-fileserver `FileLifecycleController`가 부르는 inbound 포트라 `INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`(architectureTest)가 구체 클래스 의존을 금지(없앴다가 architectureTest FAIL로 복원), `CleanupService`·`FileReconciliationService`는 composition `FileserverCleanupWorkerTest`·`FileserverStructuredLoggingTest`가 람다/익명 대역으로 구현(두 번째 구현 존재 — 현황표 근거 "fake 없음"이 틀림). `FileserverUseCaseContractDeviationTest.KNOWN_DEVIATIONS` 갱신 | - | 인터페이스 6개 삭제, `Default*`를 인터페이스 이름으로 개명 | -| S1-#6b | Required | fileserver 인바운드가 use-case 계약 밖(capability gate 미적용) | 남음 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): 사유: 결정 필요 — transport 연산 약 30개를 `CommandUseCase`/`QueryUseCase` + `@UseCaseCapability`로 바꾸면 `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`(architectureTest) 때문에 쓰기 연산마다 `@RequiresPermission("file:…")`이 필요하고, 그 annotation은 web `RequiresPermissionAuthorizationManager`가 `AuthorizationPort`로 런타임에 강제한다. 즉 기존 `FileAccessPolicyPort`(역할·소유자 검사, C-8a) 위에 권한 게이트가 하나 더 생기고, 배포는 새 권한 이름을 부여해야 기존 업로드·다운로드가 계속 된다. (1) fileserver 연산에 method-security 권한을 추가할지(추가하면 권한 이름 체계), 아니면 (2) `RepositoryAccess`/권한 규칙에서 fileserver를 예외로 둘지를 정해야 한다(`docs/fileserver/design-deviations.md` §5가 ADR로 열어 둔 질문). 승인자: 저장소 소유자 결정 필요
결정 32(2026-09-28): 권한 추가로 결정 → 남음, P28 | W3 | transport가 부르는 연산을 `*UseCase` + `@UseCaseCapability`로 선언 | +| S1-#6b | Required | fileserver 인바운드가 use-case 계약 밖(capability gate 미적용) | 완료 | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 W3 `b06b4166`(결정 32). transport가 부르는 21개 연산을 `application-fileserver/.../port/in/*UseCase`(연산 하나씩, `CommandUseCase`/`QueryUseCase`) + `*Command`/`*Query`로 선언하고 구현 `*ApplicationUseCase`(upload·download·lifecycle·admin 패키지)에 `@UseCaseCapability`를 단다. 권한: `file:read`(describe·prepare·open·transfer·upload status), `file:upload`(create·append·finalize·cancel·single-request upload), `file:delete`, `file:copy`, `file:move`, `file:admin`(관리 plane 8개). `FileAccessPolicyPort`(tier·소유자·tenant)는 각 use case 안에서 그대로(결정 32 "둘 다"). `security.yml` `"[ROLE_FILE_READ]": file:read`, `"[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move`, `"[ROLE_FILE_ADMIN]": file:admin`(fileserver 기본 tier 역할 이름을 key로 — 한 역할이 권한과 tier를 함께 준다), dev Keycloak realm에 같은 client role 3개(`ROLE_FILE_ADMIN`은 서비스 계정에 미부여), `docs/fileserver/design-deviations.md` §5·`configuration.md`·`infra/keycloak/README.md`. 조립은 `composition:fileserver-platform`의 `FileserverUploadUseCaseConfiguration`·`FileserverFileUseCaseConfiguration`·`FileserverAdminReadUseCaseConfiguration`·`FileserverAdminActionUseCaseConfiguration`(BOOT-007 8-bean 한도), adapter의 download/lifecycle/admin 서비스 조립 삭제. 테스트: `FileserverCompositionIntegrationTest.anUploadByATierWithoutTheUploadPermissionIsRefusedBeforeAnythingIsStaged`(실제 PG, `MethodSecurityConfig` 없이 FAIL 1건 → 포함 PASS; fileserver tier는 통과하지만 권한 매핑이 없는 역할 `ROLE_UNMAPPED_WRITER`), 같은 클래스 3건 PASS; `BlockingTransferExecutorSecurityContextTest.workOnTheTransferPoolSeesTheCallersAuthentication` FAIL(assertion) → PASS(전송 풀 작업에 요청 SecurityContext 전달 — 없으면 append·finalize·download stream이 권한 게이트에서 익명으로 거부됨). ArchUnit: fileserver access policy 패키지(`adapter.outbound.fileserver.platform.security`, IO 없음)를 D7 in-process driven outbound로 추가(`ApplicationBoundaryArchitectureTest.isInProcessDrivenOutbound`), `FileserverUseCaseContractDeviationTest` 동결 목록을 `DefaultCleanupService`·`DefaultFileReconciliationService`·`WriterLeaseCoordinator`로 축소(배경 작업은 caller identity가 없어 권한을 가질 수 없음). `:app-bootstrap:architectureTest` PASS. 수정 방향과 다른 점: 트랜잭션을 열지 않던 append·status·download read·incomplete-list는 `USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY` 때문에 해당 경계(`inWrite`로 lease commit 감쌈 — coordinator 경계에 join, `inRead`로 조회)를 직접 연다; 여러 use case를 합성하는 single-request upload·operator cleanup은 `RepositoryAccess.NONE`(각 단계가 자기 경계를 연다) | - | transport가 부르는 연산을 `*UseCase` + `@UseCaseCapability`로 선언 | | S1-#7 | Consider | 에러 코드마다 예외 서브클래스, 타입 분기는 몇 개뿐 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `6d6c69fe`. `FileserverException`을 구체 클래스로(`api/error/FileserverException.java:37` `of(code, message)`, `notReady(fileId, state)`). catch/instanceof로 타입 분기하는 5개(`FileNotFoundException`·`FileAlreadyExistsException`·`InvalidPathException`·`UploadOffsetMismatchException`·`AmbiguousCompletionException`)만 남기고 17개 삭제, 생성 지점 약 110곳을 `new FileserverException(message, context)`/`FileserverException.of(CODE, …)`로. 테스트의 타입 분기(`MvcUploadExecutorSaturationTest`, PG `aReleasedReservationCanNeverBeCommittedOrExtended`)는 `code()` 비교로. fileserver 5개 leaf `check`·PG lane 3개 PASS | - | base를 구체 클래스 + `of(code, …)`, 서브클래스는 catch로 타입 분기하는 5개만 남김 | | S1-#8 | Consider | `PolicyTransactionPort` 계열이 호출 1곳용 | 해당 없음(코드 삭제) | 「제거된 코드」 `PolicyTransactionPort` 계열·`SpringPolicyTransactionPort`·`FileserverCompensationTransaction` 행. grep 0건 | - | - | | S1-#9 | Consider | 같은 전략만 담은 레지스트리 2개 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): `TemplateRendererRegistry`·`MapTemplateRendererRegistry`·`ThymeleafNotificationRenderer`, `ProviderEventProjectorRegistry`·`MapProviderEventProjectorRegistry`·`SesDeliveryProjector` 삭제(`bff135d6`). renderer 하나(`CanonicalNotificationRenderer`, channel은 `RenderCommand`에서; `NotificationPlatformProviderConfig.java:53`)와 projector 하나(`StandardDeliveryProjector`; `NotificationPlatformRegistriesConfig.java:38`)를 직접 주입. `ProviderEventProjector.providerId()`·`NotificationTemplateRenderer.channel()`, `AssembledProvider`/`AssembledPlatform`의 projector 슬롯, `ProviderCallbackAssembler.projector()`, `NO_PROJECTOR` 분기 삭제. 테스트 `NotificationProviderAssemblyTest.anSesHardBounceIsProjectedByTheSharedProjector` PASS. PG 테스트 `PostgreSqlNotificationBackgroundPassIntegrationTest.replayMarksAnEventWithNoProjectorFailed`는 그 분기가 없어져 삭제 | - | 레지스트리·`Map*Registry` 삭제, 구현체 직접 주입 | @@ -801,7 +801,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S1-#17a | Consider | objectstorage 식별자 클래스 6개·가드 2개 복사 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `7a21c6e7`. `ObjectId`·`ObjectReference`·`ObjectStageHandle`·`ObjectVersionToken`을 compact constructor + `toString`(redacted) record로(`identity/ObjectId.java:4`). `DirectTransferSessionId`·`PartReceiptToken`은 D-7a에서 이미 삭제. 가드는 `ObjectModelSupport.requireBoundedToken`(`model/ObjectModelSupport.java:9`) 하나, `ObjectRequestSupport.boundedToken` 삭제. `:application-objectstorage:check`, control record 골든 digest(`ObjectControlRecordCodecTest`) PASS | - | 식별자를 record + `toString` 재정의로, 가드는 하나로 | | S1-#17b | Consider | legacy `application.storage` 네임스페이스 공존(Javadoc 모순) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `e8b6bae0`. sample에는 이미 canonical 포트 위의 `PublishPosterImageUseCase`(mode=publication)가 있어 legacy mode(`UploadPosterImageUseCase`·`LegacyPosterImageController`)를 지우고 local/test profile은 `mode: disabled`. `application.storage.ObjectStoragePort`·`StoredObject`와 legacy 어댑터 2개 삭제. `:sample-portfolio:check`·`systemTest` PASS | - | 「한 기능에 한 세대」: sample `UploadPosterImageUseCase`를 `application.objectstorage` 포트로 옮기고 legacy 포트·어댑터 2개 삭제 | | S1-#18a | Consider | `V2` 접미사 타입 | 완료 | `6d27356e`: 멱등성 V2 → 무접미사, outbox V2 삭제. main의 `*V2*.java`는 sample 이벤트 스키마 버전 `PosterImageAttachmentReadyV2` 하나뿐 | - | - | -| S1-#18b | Consider | 포트·서비스 이름 규칙이 leaf마다 다름 | 남음 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): outbound 부분은 완료(`18ed5e7d`): `FileQuotaService`→`FileQuotaPort`, `FileMetadataStore`→`FileMetadataPort`, `UploadSessionStore`→`UploadSessionPort`, `*Gateway` 8개→`*Port`, 그 밖의 outbound 포트 9개에 `Port` 접미사(어댑터 구현 이름은 유지). 남은 inbound `*Service`→`*UseCase` 개명은 S1-#6b와 같은 결정에 묶인다 — 이름이 `UseCase`로 끝나고 `TransactionPort`를 쥔 클래스는 `ORCHESTRATION_ENTRYPOINTS_DECLARE_A_CAPABILITY`로 `@UseCaseCapability`가, 쓰기면 `@RequiresPermission`이 필요하다. 승인자: 저장소 소유자 결정 필요(S1-#6b와 함께)
결정 32(2026-09-28): 권한 추가로 결정 → 남음, P28 | W3 | 소유자 규칙대로 outbound `*Port`, inbound `*UseCase`로 기계적 개명 | +| S1-#18b | Consider | 포트·서비스 이름 규칙이 leaf마다 다름 | 완료 | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 W3 `b06b4166`: inbound `UploadApplicationService`·`DownloadApplicationService`·`FileLifecycleService`·`FileserverAdminService`·`SingleShotUploadService`·`FinalizeUploadService`와 `Default*` 구현을 `port.in/*UseCase` + `*ApplicationUseCase`로(notification의 `port.in` 규칙과 같음). 남긴 `*Service`는 transport가 부르지 않는 배경 작업 `CleanupService`·`FileReconciliationService`뿐 — 쓰기 use case는 `@RequiresPermission`이 필수인데 scheduler는 권한을 가질 caller가 없으므로 use case로 만들면 매 실행이 거부된다(`FileserverUseCaseContractDeviationTest` 주석) | - | 소유자 규칙대로 outbound `*Port`, inbound `*UseCase`로 기계적 개명 | | S1-#19 | Nit | 이력 주석·inline FQN | 남음 | 재측정: 이력 문구("used to" 등) application-core 14·notification 23·fileserver 9·objectstorage 1줄, notification inline FQN 74줄 | W5 | 불변 조건 1~2줄만 남기고 이력은 git/ADR로, FQN은 import로 | | S1-#20 | Nit | notification `dispatch/` 패키지에 여러 기능 | 남음 | `application-notification/.../platform/dispatch/` 46파일 3,855줄(제출·템플릿 게시·`ContactPoint*`·reconciliation 포함) | W5 | `submission/`, `dispatch/`, `reconciliation/`로 이동, `ContactPoint*`는 `contact/`로 | | S1-lead-1 | 권고 | messaging 자체 outbox/inbox와 app-core outbox/inbox가 같은 패턴 3~4벌 | 완료 | app-core inbox 삭제(「제거된 코드」 same-store inbox 행), outbox V2 삭제. 남은 2벌(app outbox + vendored `messaging_outbox`)은 D2 결정(`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md:104` "messaging platform outbox는 vendored라 유지") | - | - | @@ -821,14 +821,14 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S2-#6a | Required | owner-lease claim 절차·`digestFields` 복사(inbox·polling) | 해당 없음(코드 삭제) | `PostgreSqlSameStoreInboxAdapter`·`PostgreSqlPollingDeliveryAdapter`·`PostgreSqlImmutableOutboxAppendAdapter` 삭제(「제거된 코드」 same-store inbox, JPA outbox V2 adapter 행). claim 절차는 멱등성 store에만 남음 | - | - | | S2-#6c | Required | `capability_schema_registry` 확인 SQL 복사 | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 추출 뒤 persistence-jpa 안의 `capability_schema_registry` 확인 SQL은 `PostgreSqlOwnerSafeIdempotencyStore.java:66` 하나뿐. notification 사본(`persistence-notification/.../NotificationSchemaActivation.java:29`)은 fileserver와 같은 처지(jpa edge 없는 capability leaf)가 되어 행의 "fileserver는 자기 사본 유지" 규칙을 그대로 따름. 두 capability의 공용화(support로)는 P18(idempotency 이동)·P24(fileserver)와 겹쳐 이번에 하지 않음 | - | persistence-jpa 안 2곳은 `CapabilitySchemaRequirement` record 하나로, fileserver는 jpa edge가 없어 자기 사본 유지(또는 support로) | | S2-#7 | Required | JPA 플랫폼 라이브러리가 지원 표면 밖 | 완료 | 단일 구현 인터페이스 8개 grep 0(「제거된 코드」 work-claim·upsert 실행기, 단일 구현 인터페이스 행), 남은 라이브러리는 소유자 결정(Wave 3)대로 `adapter/outbound/persistence-jpa/README.md:61` 라이브러리 API 표에 명시. main 26.3k→20.0k줄 | - | - | -| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 남음 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java`(스캔 stereotype 16개), `notification/configuration/NotificationJpaPersistenceFacade.java`, `persistence-fileserver/.../FileserverJpaPersistenceConfig.java` + fileserver main `@ConditionalOnProperty` 10개, Mongo 6개
Wave 3 W3-P23: 미완 — 이유: 알림은 이미 feature config의 명시적 `@Bean` 한 방식(`NotificationJpaPersistenceFacade`, 이번에 이 leaf의 auto-configuration root로). 남은 대상 — `JpaAdapterComponentsConfig`의 stereotype 스캔(outbox·idempotency·lock 등), `persistence-fileserver`의 `@ComponentScan`+클래스별 `@ConditionalOnProperty`, Mongo — 은 동시에 도는 P18(outbox·멱등성 패키지 이동)·P24(fileserver)가 같은 파일을 옮기고 있어 충돌을 피해 손대지 않음. 통합 뒤 한 묶음으로 | W3 | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 | +| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 남음 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java`(스캔 stereotype 16개), `notification/configuration/NotificationJpaPersistenceFacade.java`, `persistence-fileserver/.../FileserverJpaPersistenceConfig.java` + fileserver main `@ConditionalOnProperty` 10개, Mongo 6개
Wave 3 W3-P23: 미완 — 이유: 알림은 이미 feature config의 명시적 `@Bean` 한 방식(`NotificationJpaPersistenceFacade`, 이번에 이 leaf의 auto-configuration root로). 남은 대상 — `JpaAdapterComponentsConfig`의 stereotype 스캔(outbox·idempotency·lock 등), `persistence-fileserver`의 `@ComponentScan`+클래스별 `@ConditionalOnProperty`, Mongo — 은 동시에 도는 P18(outbox·멱등성 패키지 이동)·P24(fileserver)가 같은 파일을 옮기고 있어 충돌을 피해 손대지 않음. 통합 뒤 한 묶음으로
Wave 3 W3-P28: 미완 — 한 것(P28 W3 `537310f9`): persistence-fileserver의 `@ComponentScan` + store 9개 클래스별 `@Repository`·`@ConditionalOnProperty`를 없애고, 조건 한 곳(`FileserverJpaPersistenceConfig`, 이 leaf의 `AutoConfiguration.imports` root) + 명시적 `@Bean` 설정 둘(`FileserverJpaMetadataStoreConfig`·`FileserverJpaQueueStoreConfig`)을 `@Import` — notification(`NotificationJpaPersistenceFacade`)과 같은 방식. web-fileserver 컨트롤러 4개·예외 처리기가 조립 root가 이미 거는 `app.fileserver-platform.enabled`를 반복하던 것 삭제(tus·draft12·admin은 자기 스위치만). 검증: persistence-fileserver·web-fileserver·composition fileserver `check`, PG lane `postgresqlFileserver{Metadata,Reclamation}IntegrationTest` 15·15, `FileserverCompositionIntegrationTest` 3 PASS. 남은 것: persistence-jpa `JpaAdapterComponentsConfig`의 8개 패키지 stereotype 스캔. 이유: 스캔이 있는 까닭이 이 leaf의 패키지 경계 목록(`JpaModuleBoundaryTest.PACKAGE_CATALOG`)이 `config`/`autoconfigure` → `audit`·`failure`·`liveevent`·`lock`·`operation`·`outbox` edge를 허용하지 않기 때문이다 — 명시적 `@Bean`으로 바꾸려면 (a) `autoconfigure`에 6개 edge를 추가하거나 (b) 패키지마다 capability 스위치를 반복하는 auto-configuration을 두어야 해서 leaf 내부 모듈 지도 결정이 먼저다(`JpaAdapterComponentsConfigTest`·`PersistenceEntityScanCoverageTest`가 스캔 계약을 고정). Mongo는 이미 자기 `AutoConfiguration.imports` 둘 + `@Bean` 방식이라 변경 없음(남은 것은 `MongoPlatformAutoConfiguration`의 bean별 조건 반복 19개) | W3 | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 | | S2-#8b | Consider | "두 조립 루트가 `dev.caskeleton.adapter`를 스캔한다" 서술이 사실과 다름 | 남음 | `persistence-jpa/.../postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java:53`, `src/test/.../CandidateAdapterCompositionTest.java:10-18`(현재 `CaSkeletonApplication`은 scan 제외식 없음, sample은 `SamplePortfolioApplication.java:31-40`처럼 좁게 스캔) | W5 | 잘못된 단락 삭제, 전제가 사라진 `CandidateAdapterCompositionTest` 삭제 또는 현재 조립 기준으로 재작성 | | S2-#9a | Consider | 무관한 `inbox` 패키지 2개 | 해당 없음(코드 삭제) | `postgresql/inbox` 삭제(「제거된 코드」 same-store inbox 행) | - | - | | S2-#9b | Consider | feature가 vendor별로 흩어짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 이동만 했다(`910ab7ab`). 새 패키지는 `persistence/outbox/{jpa(+entity),postgresql,h2}`, `persistence/idempotency/{jpa(+entity),postgresql}`다. JPA API surface는 `updateJpaApiSurface -PapproveJpaApiSurfaceChange`로 다시 승인했다. `JpaModuleBoundaryTest`에 autoconfigure→idempotency edge를 기록했다. `verifyJpaApiSurface`·`verifyJpaReadinessRegistry` PASS. | - | feature 기준 패키지(`outbox/{jpa,postgresql,h2}`, `idempotency/{jpa,postgresql}`)로 이동만 | | S2-#10 | Consider | promotion/benchmark gate가 production classpath에 | 해당 없음(코드 삭제) | 「제거된 코드」 `experimental/next/*`, `MongoAdvancedPromotionGate`·`Evidence`, search·vector(benchmark·readiness gate 포함) 행. grep 0 | - | - | | S2-#12 | Consider | Javadoc이 이력을 서술 | 남음 | 재측정: "used to/until now/never was/no longer" 포함 파일 jpa 25·mongo 36·fileserver 6 | W5 | 불변 조건 1~2줄만 남기고 이력은 git/ADR로 | | S2-#13a | Nit | `JpaTransactionAutoConfiguration` 팩토리 2회 생성, `new JpaTransactionSettings(null ×9)` | 해당 없음(코드 삭제) | 「제거된 코드」 두 번째 엔진(`JpaTransactionAutoConfiguration`)·`JpaTransactionSettings` 행 | - | - | -| S2-#13b | Nit | port 구현 이름 규칙 7가지 | 남음 | `OutboxStoreAdapter`, `CanonicalOutboxAppendAdapter`, `Jpa*Store`(notification), `JdbcReconciliationJobStore`, `PostgreSqlOwnerSafeIdempotencyStore`, `SpringTransactionPort`, `LockRegistryDistributedLockAdapter`, `persistence-fileserver/.../JpaFileQuotaService`
Wave 3 W3-P23: 미완 — 알림 부분만 완료: `JpaNotificationSideEffectStore` → `JpaNotificationSideEffect`(`NotificationSideEffectPort`), 나머지 알림 구현은 이미 ``(`JdbcReconciliationJobStore` 포함). 이유: 행에 열거된 나머지(`OutboxStoreAdapter`, `CanonicalOutboxAppendAdapter`, `PostgreSqlOwnerSafeIdempotencyStore` — P18, `JpaFileQuotaService` — P24, `SpringTransactionPort`·`LockRegistryDistributedLockAdapter` — core)는 다른 묶음 소유이고 S1-#18b와 함께 기계적 개명으로 해야 함 | W3 | `` 규칙 하나로 개명(S1-#18b와 함께) | +| S2-#13b | Nit | port 구현 이름 규칙 7가지 | 완료 | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 W3 `2619cb18`: 규칙 `<포트 이름에서 Port를 뺀 것>` 하나로 24개 개명(테스트 클래스 이름 포함). persistence-fileserver `JpaFileMetadata`·`JpaFileQuota`·`JpaQuotaCommit`·`JpaQuotaReclaim`·`JpaUploadSession`(이미 규칙대로인 `JpaCleanupQueue`·`JpaContentReferenceLedger`·`JpaRecoveryQueue`·`JpaStagingUploadLocator`는 유지); fileserver adapter `LocalCleanupContent`·`LocalCopyContent`·`LocalOrphanScan`·`LocalReconciliationContent`·`LocalStorageHealth`·`LocalStorageUsage`·`LocalUploadContent`·`LocalUploadStorage`·`StructuredAdminAudit`·`StructuredFileserverAudit`·`RandomUploadIdentifier`; persistence-jpa core `SpringTransaction`·`JpaOutboxStore`·`JpaDurableOperationStore`·`PostgreSqlIdempotencyStore`·`LockRegistryDistributedLock`·`MeteredDistributedLock`·`DomainContextAuditContext`·`JpaLiveEventReplay`. 행에 적힌 `CanonicalOutboxAppendAdapter`는 P18에서 이미 삭제됨. 유지(이유): `LocalBlockingContentStore`(포트 3개를 구현하는 store 자체), `VerificationCoordinator`(verifier 파이프라인 합성 — 기술 어댑터가 아님), `RoleBased`/`UnenforcedFileAccessPolicy`(이미 `<정책>`). 문서·README·CLAUDE.md의 단순 이름과 PG 통합 테스트의 bean 이름 문자열도 갱신. API surface 재승인(`updateJpaApiSurface -PapproveJpaApiSurfaceChange`, `updatePersistenceFileserverApiSurface -PapprovePersistenceFileserverApiSurfaceChange`, 개수 증가 없음). persistence-jpa·persistence-fileserver·fileserver·composition fileserver·idempotency·application-core·notification·persistence-notification `check`, `:app-bootstrap:architectureTest`·`test` PASS | - | `` 규칙 하나로 개명(S1-#18b와 함께) | | S2-#14a | Nit | jpa CLAUDE.md의 "NoSQL은 미래 모듈"·MapStruct 절이 현실과 다름 | 남음 | `adapter/outbound/persistence-jpa/CLAUDE.md:17-19,202-206`(Mongo leaf 이미 존재), `:309-330` MapStruct 절(의존성 없음) | W5 | NoSQL 문장을 현재 leaf 기준으로 고치고 MapStruct 절 삭제 | | S2-#14b | Nit | jpa API surface 파일에 옮겨간 타입 | 남음 | `docs/architecture/jpa-adopter-api-surface.txt:11` `...persistence.fileserver.FileserverSchemaActivation`(지금은 persistence-fileserver leaf) | W5 | 해당 줄 삭제(필요하면 fileserver 쪽 surface로) | | S2-#14c | Nit | Mongo CLAUDE.md `MongoAdvancedProperties` 오기 | 완료 | `6d27356e`: 해당 이름 없음, `adapter/outbound/persistence-mongo/CLAUDE.md:146`이 "flags have no configuration property"로 갱신(`MongoAdvancedSettings`도 삭제) | - | - | @@ -907,7 +907,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S4-#17a | Nit | fileserver `*Config`/`*Configuration` 혼재, 클래스 이름의 버전 라벨 | 해당 없음(코드 삭제) | 루트 `*Config`(`FileserverR2Config` 등)와 `R2PublishedReferenceCodec` 삭제. 남은 fileserver 설정 8개는 모두 `*Configuration` | - | - | | S4-#17b | Nit | notification `*ProviderProperties`는 `@ConfigurationProperties`가 아닌 파생 값 | 남음 | `Apns`/`Fcm`/`Ses`/`Smtp`/`Twilio`/`WebPushProviderProperties` 6개. 어느 것도 `@ConfigurationProperties`가 아님 | W5 | #3a 이후 남는 `Ses`·`SmtpProviderProperties`를 `*ProviderProfile`로 이름 변경 | | S4-lead-1 | 권고 | 손으로 만든 canonical JSON codec이 3개 leaf에 있음 (= X1-8) | 해당 없음(코드 삭제) | fileserver 2벌·messaging `DeterministicEnvelopeWriter` 삭제. 남은 건 objectstorage `control/CanonicalJson{Reader,Writer}.java` 하나라 중복 아님 | - | - | -| S4-lead-2 | 권고 | 로컬 보안 파일시스템 primitive가 fileserver·objectstorage에 따로 있음 | 남음 | fileserver `platform/local/SafeFileChannelFactory.java:250`(`SecureDirectoryStream`)·`SecureDirectoryWalk.java`. objectstorage `filesystem/LocalObjectPathGuard.java:62-117`은 경로 검사 후 사용 방식(`rejectExistingLinks` → 생성). 방식과 검사가 다름. objectstorage는 `adapter-outbound-support` edge가 없음
Wave 3 W3-P24: 미완 — 이유: fileserver primitive 중 `SecureDirectoryWalk`는 JDK만 쓰지만 `SafeFileChannelFactory`는 `IOException`을 Fileserver 에러 코드로 바꾸는 번역을 품고 있어, support로 올리려면 에러 어휘를 떼어 내야 한다. 그리고 objectstorage `LocalObjectPathGuard`는 Path를 돌려주고 호출자(`LocalDevObjectDataStore`·`LocalDevObjectControlStore`·`LocalObjectStreamTransfer`, 약 520줄)가 `Files.*`로 여는 구조라, primitive를 쓰려면 이 I/O를 fd 기준(`SecureDirectoryStream`) 연산으로 다시 써야 한다. registry edge 추가만으로는 끝나지 않는 보안 민감 재작성이라 별도 묶음(권고 행)으로 남김 | W3 | fileserver 쪽 primitive를 `adapter:outbound:support`로 올리고, objectstorage에 support edge를 추가해서 `LocalObjectPathGuard`가 그것을 쓴다(registry 수정 포함) | +| S4-lead-2 | 권고 | 로컬 보안 파일시스템 primitive가 fileserver·objectstorage에 따로 있음 | 남음 | fileserver `platform/local/SafeFileChannelFactory.java:250`(`SecureDirectoryStream`)·`SecureDirectoryWalk.java`. objectstorage `filesystem/LocalObjectPathGuard.java:62-117`은 경로 검사 후 사용 방식(`rejectExistingLinks` → 생성). 방식과 검사가 다름. objectstorage는 `adapter-outbound-support` edge가 없음
Wave 3 W3-P24: 미완 — 이유: fileserver primitive 중 `SecureDirectoryWalk`는 JDK만 쓰지만 `SafeFileChannelFactory`는 `IOException`을 Fileserver 에러 코드로 바꾸는 번역을 품고 있어, support로 올리려면 에러 어휘를 떼어 내야 한다. 그리고 objectstorage `LocalObjectPathGuard`는 Path를 돌려주고 호출자(`LocalDevObjectDataStore`·`LocalDevObjectControlStore`·`LocalObjectStreamTransfer`, 약 520줄)가 `Files.*`로 여는 구조라, primitive를 쓰려면 이 I/O를 fd 기준(`SecureDirectoryStream`) 연산으로 다시 써야 한다. registry edge 추가만으로는 끝나지 않는 보안 민감 재작성이라 별도 묶음(권고 행)으로 남김
Wave 3 W3-P28: 미완 — 한 것(P28 W3 `da49df6c`): fileserver의 descriptor 기반 primitive를 `adapter/outbound/support/.../support/filesystem/SecureDirectoryWalk.java`(이동, public)·`SecureFileAccess.java`(신규: createNew·openForRead/Write·deleteRegularFile·readAttributes·isRegularFile·createParentDirectories)로 올리고, 거부를 에러 코드 없는 타입 있는 `IOException`(`SymbolicComponentException`·`PathEscapeException`·`NotRegularFileException`)으로. fileserver `SafeFileChannelFactory`는 위임 + `LocalStorageFailures` 번역만(P24 메모대로 번역 분리). 테스트: `SecureFileAccessTest` 8건(symlink leaf·symlink 디렉터리 component·`..` 탈출·create-only 충돌·symlink delete 거부·열린 뒤 디렉터리를 link로 바꾸는 race `aDirectorySwappedForALinkAfterItWasOpenedDoesNotRedirectTheOperation`), `SecureDirectoryWalkTest` 2건(support로 이동), `LocalStorageFailuresTest` 2건 FAIL→PASS(P28-new-1). fileserver·support `check`, PG lane `postgresqlFileserver{Migration,Metadata,Reclamation}IntegrationTest` 6·15·15 PASS. 남은 것: objectstorage `LocalObjectPathGuard`를 이 primitive로 바꾸는 재작성(과 objectstorage→support registry edge). 이유: local-dev provider의 쓰기는 "없거나 완전한" 게시를 위해 임시 파일을 `Files.createLink`(link(2))로 create-only 연결하는데, `SecureDirectoryStream`에는 linkat이 없고 `move`는 기존 대상을 덮어쓴다(renameat2 NOREPLACE 미노출). descriptor 기반으로 바꾸면 create-only 원자 게시를 잃거나(대상 선점 후 덮어쓰기 — 읽는 쪽이 빈/부분 객체를 볼 수 있음) native 호출이 필요해 설계 결정이 먼저다. 읽기·retire 경로만 바꾸면 쓰기 경로의 race가 남아 "한 primitive"가 되지 않으므로 이번 묶음에서는 손대지 않음(대상은 local-dev 전용 provider) | W3 | fileserver 쪽 primitive를 `adapter:outbound:support`로 올리고, objectstorage에 support edge를 추가해서 `LocalObjectPathGuard`가 그것을 쓴다(registry 수정 포함) | | S4-lead-3 | 권고 | notification 자체 JDK HTTP gateway·SigV4 서명기 vs httpclient leaf·AWS SDK | 완료 | Wave 3 W3-P23 (Wave 3 라운드 3 커밋): 소유자 결정 17. `SesNotificationProviderAdapter.java:113` `client.sendEmail`(AWS SDK v2 `sesv2` 2.30.0, 카탈로그 `awsSdk`·SDK BOM, objectstorage와 같은 버전). client는 `SesClients.java`: SDK 재시도 끔(`:54` `AwsRetryStrategy.doNotRetry()`), 기본 자격 증명 체인 대신 던지는 provider, 설정 endpoint(라우팅 가드 통과)를 `endpointOverride`, Apache client(redirect 안 따라감). 자격 증명은 기존 계약 유지(설정 `access-key-id` + `ProviderCredentialManager`의 프로필·세대별 secret)로 요청마다 `AwsRequestOverrideConfiguration`에 실음. `JdkNotificationHttpGateway`·`NotificationHttpGateway/Request/Response/TransportException`·`AwsSignatureV4Signer`·`notificationHttpGateway` bean 삭제. SNS 인증서 fetch는 callback 설정 안의 redirect 없음·64KiB 상한 JDK 요청. 검증: SDK client를 로컬 HTTP 가짜(`ProviderFaultHarness`)에 `endpointOverride`로 붙인 계약 테스트 `SesNotificationProviderAdapterTest` 17건(수락·거절·응답 유실=AMBIGUOUS·throttle·첨부 raw MIME·프로필별 서명·경로 `/v2/email/outbound-emails`) + 새 `theSdkRetriesNothingSoAServerErrorIsOneRequest`·`aMessageRejectedAnswerIsAPermanentRejection` PASS, `CrossProviderContractSuiteTest` 5건 PASS. env 키·설정 키 변경 없음 | - | 결정(2026-09-25): AWS SDK(sesv2)로 교체, 자체 JDK gateway·SigV4 서명기 삭제 | | S4-lead-4a | 권고 | adapter `LocalJsonSchemaRegistry` vs vendored `messaging-schema-json` | 해당 없음(코드 삭제) | `LocalJsonSchemaRegistry` grep 0건. 「제거된 코드」 표 123행 | - | - | | S4-lead-4b | 권고 | `adapter:outbound:messaging-kafka`(R0 seam) vs vendored `messaging/messaging-kafka` | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** `core/MessageBroker` 계열(MessageBroker, MessagePublisher, OutboundMessage, OutboundMessagePublisher, DisabledMessagePublisher)과 `OutboxEnvelopeJson`, `adapter:outbound:messaging-kafka`의 Java 코드 전부.
**relay 경로:** relay는 claim한 row의 `ValidatedIntegrationEvent`를 bridge로만 보낸다(`OutboxMessagePublishAdapter(IntegrationEventPublishPort)`, `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java:23`).
**leaf를 남긴 이유:** 계획은 leaf 삭제였다. 대신 bridge+starter-kafka를 싣는 코드 없는 capability 묶음으로 남겼다. 한 줄 선택이 유지되고, bridge leaf는 broker 중립으로 남는다.
**테스트:** `KafkaCapabilityActivationTest` PASS. | - | legacy `OutboxEvent`에 canonical metadata를 채우는 migration 후 relay를 bridge로 바꾸고 `adapter:outbound:messaging-kafka`와 `core/MessageBroker` 계열 삭제 | @@ -982,7 +982,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop): | S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **새 leaf `composition:service-runtime`**(`dev.caskeleton.composition.runtime`, edge application-core, shared-contract, adapter-outbound-support, adapter-outbound-identifier):
- 원본을 app-bootstrap에서 옮겼다: `tracing`(TracingConfig 외 5), `metrics`(MetricsContractConfig+filter 2), `context`(DomainContextConfig/Settings), `logging`(PseudonymizationConfig, PrivacySettings), `management/security`(ManagementSecurityConfig).
- 모두 이 모듈의 `AutoConfiguration.imports`로, sampling bridge는 `spring.factories`로 등록한다.
- app-bootstrap과 sample이 `runtimeOnly project(':composition:service-runtime')`를 쓴다.
**sample:** 복사본 10개와 `spring.factories`를 삭제했다. 원본을 쓰므로 `staging=0.10` 분기도 사라졌다.
**sample actuator chain:** 복사본이 아니라 공개 데모라는 샘플만의 결정이라 남겼다. bean 이름을 `actuatorSecurityFilterChain`으로 바꿔 공용 chain이 물러나게 했다(`ConditionalOnMissingBean(name)`).
**테스트:** `ServiceRuntimeRegistrationTest` 4개(신규), 옮긴 테스트 9 클래스 — `:composition:service-runtime:test` 86 PASS. `ActuatorSecurityHttpTest`, `DefaultCompositionBootTest`, `StartupOrderContractTest`, `ConfigurationNamespaceContractTest` 갱신 후 PASS. | - | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 | | S6-#8 | Required | sample root가 다른 leaf 패키지를 넓게 scan | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SamplePortfolioApplication`: `@ComponentScan("dev.caskeleton.sample")`·`@ConfigurationPropertiesScan("dev.caskeleton.sample")`, 제외는 `WebSecurityAutoConfiguration` 하나(`SamplePortfolioApplication.java:31-32`). web·objectstorage는 각 auto-config로. `SamplePublicAccessSecurityConfigTest.sampleCompositionRootExcludesOnlyTheWebSecurityRoot`·`sampleCompositionRootScansOnlyTheSamplePackage`(옛 exclude-filter 단언 대체). sample `test`·`integrationTest` 51·`systemTest` 3·`webSystemTest` 5 PASS | - | scan을 `dev.caskeleton.sample`로 좁히고 web·identifier·objectstorage는 각 leaf auto-config로 받기(보안 설정 2개는 exclude/property로 끔) | | S6-#9 | Required | sample `application.yml` 중 읽는 코드 없는 블록 | 남음 | 326줄 중 약 101줄: `src/sample-portfolio/src/main/resources/application.yml:150-177`(capabilities.cache), `:180-181`(bootstrap), `:210-226`(logging), `:255-279`(app.cache.redis), `:280-283`(messaging), `:284-288`(notification), `:289-308`(outbound.http). sample classpath에 해당 binder 없음(`src/sample-portfolio/build.gradle:48-83`) | W5 | 해당 블록 삭제 | -| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존
Wave 3 W3-P25: 미완 — 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 | +| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존
Wave 3 W3-P25: 미완 — 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다
Wave 3 W3-P28: 미완 — / P28 에이전트가 세션 재시작으로 중단(미커밋) — P30으로 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 | | S6-#10b | Consider | poster-image legacy API 모드 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `LegacyPosterImageController`·`UploadPosterImageUseCase`·`UploadPosterImageCommand`·`LegacyPosterImageAttachment`·`PosterImageApiConfig`·`PosterImageApiSettings`(LEGACY 모드)·`Poster.attachImage`·`Poster.imageKey()`·dual-read `rehydrate` 삭제. `PosterEntity`는 `image_key`를 매핑하지 않고, CAS attach가 `image_key = NULL`로 pre-V8 행을 정규 경로로 받는다(`PosterImageAttachmentCasRepository.java:32`). `PosterRepositoryAdapterIntegrationTest.aPreV8RawKeyRowReadsBackWithoutAnImage`·`canonicalAttachClearsAPreV8RawKeyOnTheSameRow` PASS(삭제에 따른 새 동작이라 FAIL 재현 없음). `PosterResponse.imageKey` wire 이름은 유지하고 published reference를 싣는다. sample `local` 프로필·systemTest yml의 `mode: legacy`·`object-storage.legacy` 블록 삭제 | - | legacy 모드와 전용 타입 삭제 | | S6-#10c | Consider | 상태 머신이 application 계층, use case 생성자 14개 | 완료(부분 수정 방향 변경) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `PublishPosterImageUseCase` 설정값 인자(destination·epoch·intentTtl·handoffLease)를 `PosterImagePublicationParameters` record 하나로(생성자 14→11, 양수 검증). 상태 머신(`PosterImageUploadIntent`)의 domain 이동은 하지 않음: 필드가 `application-objectstorage`·`application-core` 값 타입(`ObjectOperationKey`, `ObjectStageHandle`, `ObjectVersionToken`, `ObjectContentIdentity`, `ObjectMediaType`, `RequestFingerprint`)이라 domain으로 옮기면 domain→application 의존이 생긴다(HARD-STOP 1과 같은 방향 위반). sample `test` PASS | - | 상태 머신을 domain으로, 설정값 인자(TTL·lease·epoch·destination)를 record 하나로 | | S6-#10d | Consider | `WorkLogSortField`(domain)가 HTTP 이름과 persistence 이름을 같이 앎 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `WorkLogSortField`·`PosterSortField`는 논리 필드만. 요청 이름은 web mapper `SORT_FIELDS`(`WorkLogWebMapper.java:24`, `PosterWebMapper.java:19`), persistence 속성은 `sortProperty`(`WorkLogPersistenceMapper.java:57`, `PosterPersistenceMapper.java:38`). 계약 테스트·integration 51 PASS | - | 요청 이름 매핑은 web mapper로, persistence 이름은 persistence mapper로; domain enum은 논리 필드만 | @@ -1199,16 +1199,16 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P16-new-6 | 발견 | persistence-fileserver 공개 타입의 adopter import를 보는 검사가 없어짐(예전 정규식 테스트가 접두어 전체를 봤음). | 완료 | Wave 3 W3-P27 (Wave 3 라운드 3 커밋): `976c175f`: persistence-fileserver에 `ca.api-surface`, 공개 타입 24개 기준선과 adopter 목록(`FileserverSchemaActivation`) 승인 — 목록에서 빼면 composition import로 `verifyPersistenceFileserverApiSurface` 실패 | - | persistence-fileserver에 `ca.api-surface` 적용 — 빌드 잔여 묶음 | | P16-new-7 | 발견 | `docs/study/postgresql-jpa-walkthrough.ko.md` §15.6 등이 삭제된 JPA evidence manifest를 설명. | 남음 | Wave 3 P16 결과 파일 | W5 | 결정 6: 현재 코드 기준으로 갱신 | | P24-new-1 | 발견 | S3 응답 bridge가 source 무효화 전에 결과를 게시하고, 실패 원인 기록 전에 취소해 테스트가 간헐 실패(P14-new-2·P16-new-4의 원인). | 완료 | Wave 3 P24: 순서 수정, bridge 테스트 40회 반복 통과 | - | - | -| P24-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0. | 남음 | Wave 3 P24 결과 파일 | W3 | P18 통합 뒤 삭제(같은 파일) | -| P24-new-3 | 발견 | `FileVerifier`가 application-fileserver에 있지만 fileserver adapter만 쓴다. | 남음 | Wave 3 P24 결과 파일 | W3 | adapter로 이동 | +| P24-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0. | 해당 없음(코드 삭제) | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 D `a49342e2`: `PosterEventPublisher.publishImageAttached`, `domain/poster/PosterImageAttached`, `PosterImageAttachedPayload`, `PortfolioEventContracts.POSTER_IMAGE_ATTACHED`와 그 bean, `contracts/messaging/poster.image-attached/v1.schema.json` 삭제. `git grep "ImageAttached\b"` 0건. `:sample-portfolio:test` PASS | - | P18 통합 뒤 삭제(같은 파일) | +| P24-new-3 | 발견 | `FileVerifier`가 application-fileserver에 있지만 fileserver adapter만 쓴다. | 완료 | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 W3 `12f0b183`: `FileVerifier`를 `application-fileserver/.../api/security`에서 `adapter/outbound/fileserver/.../platform/verification/FileVerifier.java`로 이동(사용처는 그 패키지의 verifier 5개·`VerificationCoordinator`·`FileserverVerificationConfiguration`뿐). application은 `FileVerificationPort`만 본다 | - | adapter로 이동 | | P25-new-1 | 발견 | `TomcatWebSocketAbuseIT` shutdown 테스트가 부하 중 `20.0006s < 20s`로 한 번 실패, 재실행 4회 통과(타이밍 의존). | 남음 | Wave 3 P25 결과 파일 | W4 | 시간 경계 단언을 결정적 신호로 | -| P25-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0(= P24-new-2). | 남음 | Wave 3 P25 결과 파일 | W3 | P24-new-2와 함께(P28) | +| P25-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0(= P24-new-2). | 해당 없음(코드 삭제) | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P24-new-2와 같음(`a49342e2`) | - | P24-new-2와 함께(P28) | | P25-new-3 | 발견 | sample `local` 프로필이 기본값과 같은 `object-storage.enabled=false`만 남김. | 남음 | Wave 3 P25 결과 파일 | W5 | 불필요한 설정 삭제 또는 이유 주석 | | P18-new-1 | 발견 | messaging outbox의 손으로 쓴 header JSON reader가 `\\`로 끝나는 값에서 다음 header를 삼켰다. | 완료 | Wave 3 P18: PostgreSQL `jsonb_object`/`jsonb_each_text`, `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader` FAIL→PASS | - | - | | P18-new-2 | 발견 | root `CLAUDE.md`가 legacy outbox/realtime seam이 `src/messaging/CLAUDE.md`에 기록돼 있다고 적음(cutover 끝남). | 완료 | Wave 3 라운드 2 통합: `CLAUDE.md` Module families 문장 수정 | - | - | | P18-new-3 | 발견 | actuator security chain이 auto-configuration이 되어, web security를 직접 켜지 않은 조립은 Boot 기본 actuator chain을 받는다(설계 노트). | 남음 | Wave 3 P18 결과 파일, `composition/service-runtime/.../ManagementSecurityConfig.java` | W5 | service-runtime README에 켜짐 조건 명시 | -| P23-new-1 | 발견 | fileserver migration V1–V5가 `applied-migrations.sha256`에 고정돼 있지 않다. | 남음 | Wave 3 P23 결과 파일 | W3 | `AppliedMigrationImmutabilityTest`에 fileserver 경로 추가 + 5줄. P28 | -| P23-new-2 | 발견 | profile마다 만드는 SES SDK client를 닫지 않는다(기동 때 한 번이라 유한). | 남음 | Wave 3 P23 결과 파일 | W3 | provider 종료 시 close. P28 | +| P23-new-1 | 발견 | fileserver migration V1–V5가 `applied-migrations.sha256`에 고정돼 있지 않다. | 완료 | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 W2 `b13cf08b`: `AppliedMigrationImmutabilityTest.MIGRATION_ROOTS`에 `../persistence-fileserver/src/main/resources/db/migration` 추가 → `everyVersionedMigrationIsPinned` FAIL(`AssertionError at AppliedMigrationImmutabilityTest.java:72`, `jpa/fileserver/V1..V5` 미고정) → `applied-migrations.sha256`에 5줄 추가 후 PASS. `persistence-jpa/build.gradle` test `inputs.dir(...fileserver migration)` 추가. 새 migration 버전은 추가하지 않음 | - | `AppliedMigrationImmutabilityTest`에 fileserver 경로 추가 + 5줄. P28 | +| P23-new-2 | 발견 | profile마다 만드는 SES SDK client를 닫지 않는다(기동 때 한 번이라 유한). | 완료 | Wave 3 W3-P28 (Wave 3 라운드 3 커밋): P28 W2 `b13cf08b`: `ProviderRuntimeRegistryTest.closingTheRegistryClosesTheAdapterOfEveryRegisteredGeneration` FAIL(컴파일 실패 `cannot find symbol registry.close()`) → PASS; `SesNotificationProviderAdapterTest.closingTheAdapterClosesItsSdkClient` PASS. `SesNotificationProviderAdapter implements AutoCloseable`(`close()`→`client.close()`), `ProviderRuntime.release()`, `ProviderRuntimeRegistry implements AutoCloseable`(현재·drain 세대 모두 release) — `providerRuntimeRegistry` `@Bean`의 추론 destroy method로 context 종료 때 호출. `:adapter:outbound:notification:check` PASS | - | provider 종료 시 close. P28 | | P23-new-3 | 발견 | `app-bootstrap/build.gradle` 알림 선택 줄 주석이 persistence-jpa 줄을 함께 풀라고 함(composition이 직접 가져옴). | 완료 | Wave 3 라운드 3 통합: 주석 수정 | - | - | | ORCH-new-2 | 발견 | `NotificationPayloadAtRestContractTest`가 저장소 소스·migration을 읽지만 test inputs를 선언하지 않아(`notification/build.gradle:98`이 필요 없다고 주장) 파일이 옮겨져도 up-to-date로 건너뜀. P23 worktree에서 통과, main 통합에서 실패(옛 `persistence-jpa` 경로·`build/` 경합 walk). | 남음 | 경로와 walk 범위는 통합 때 수정(`src/main/java`만) | W4 | 읽는 파일을 test `inputs`로 선언(CLAUDE.md build-logic 규칙) | | ORCH-new-3 | 발견 | `web-advanced` `WebStreamingSoakIT.concurrent arrivals never exceed the node's ceiling`가 부하 중 `expected: 1000 but was: 1001`로 실패, 단독 3회 통과 — 상한을 1 넘는 실제 경합일 수 있다. | 완료 | Wave 3 W3-P19 (Wave 3 라운드 3 커밋): 커밋 `c3380270`. 원인: `WebStreamRegistry.register`가 `compute()` 안에서 `sessions.size()`를 읽음 — compute는 한 bin만 잠그고 크기 카운터는 잠금 해제 뒤 갱신되므로 다른 bin의 두 도착이 모두 999를 보고 삽입(실제 경합, 테스트 타이밍 문제 아님: 먼저 단언하는 `activeStreams()`가 1001). 수정: AtomicInteger CAS로 슬롯 선예약 + `putIfAbsent`, 중복·deregister는 슬롯 반환. 테스트 `stream/WebStreamRegistryAdmissionTest`(경쟁 도착 200라운드, 슬롯 반환 2건). FAIL 근거: P27 통합 ci의 `expected: 1000 but was: 1001` — 로컬에서는 수정 전 soak 형태 6회 + 200라운드로도 재현되지 않았다(창이 `addCount` 한 구간뿐). 수정 후 `WebStreamingSoakIT`+새 테스트 3회 반복 통과 | - | 재현(반복·부하)으로 경합 여부 판정, 경합이면 admission 카운터 수정. P19 | @@ -1217,8 +1217,10 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검 | P21-new-3 | 발견 | `src/messaging/CLAUDE.md`가 `MessagingPublicSurfaceContractTest`를 인용 — 테스트는 app-bootstrap에 있다(P21은 없다고 보고). 통합 때 이 테스트가 P21 변경(reactive facade 삭제, leaf 병합, starter-kafka 공개 consumer seam)을 반영하지 못해 실패 → 기대값 수정, starter-kafka에 `api kafka-clients` 선언. | 남음 | Wave 3 라운드 3 통합 | W5 | messaging CLAUDE.md의 테스트 위치 문구를 app-bootstrap 경로로 | | P22-new-1 | 발견 | bootstrap `SecretSourceValidator`가 persistence-jpa의 모듈 스위치를 읽어 `APP_DATASOURCE_PASSWORD` 필요 여부를 판정(모듈 지식이 bootstrap에). | 남음 | Wave 3 P22 결과 파일 | W3 | Redis처럼 persistence-jpa가 secret 요구를 기여. P20 | | P22-new-2 | 발견 | `infra/redis-sdk/acl/application.acl`·`all-accounts.acl`이 pub/sub 삭제 뒤에도 `+@pubsub`·`&prod:*`를 준다(최소 권한 위반, fixture). | 남음 | Wave 3 P22 결과 파일 | W3 | ACL fixture에서 제거 후 topology lane 재실행. P20 | -| P22-new-3 | 발견 | redis-sdk 공개 API가 runtime 타입을 노출하면서 runtime을 `implementation`으로만 의존. `ca.spring-library`에 `api` 구성이 없어 한 줄로 못 고침. | 남음 | Wave 3 P22 결과 파일, 통합 때 시도 | W3 | 컨벤션에 `java-library` 적용 또는 공개 표면에서 runtime 타입 제거. P29 | +| P22-new-3 | 발견 | redis-sdk 공개 API가 runtime 타입을 노출하면서 runtime을 `implementation`으로만 의존. `ca.spring-library`에 `api` 구성이 없어 한 줄로 못 고침. | 완료 | Wave 3 W3-P29 (Wave 3 라운드 3 커밋): `3967c9ef`. redis-sdk만 `java-library` + `api project(':adapter:outbound:redis-runtime')` / 통합 검증 통과(redis-sdk java-library + api redis-runtime) | - | 컨벤션에 `java-library` 적용 또는 공개 표면에서 runtime 타입 제거. P29 | | ORCH-new-4 | 발견 | redis-sdk `RedisSdkModuleBoundaryTest`·`RedisSupportMatrixTest`가 옛 split package(`redis-runtime/.../redis/sdk`)를 훑음 — P22 worktree에서 통과, main 통합에서 `NoSuchFileException`(ORCH-new-2와 같은 유형: 저장소 파일을 읽지만 test inputs 미선언). | 남음 | 경로는 통합 때 수정(`redis-sdk` 하나) | W4 | 읽는 파일을 test `inputs`로 선언 | | P19-new-1 | 발견 | notification `platform.api.TenantId`가 비어 있지 않음·100자 이하만 검사 — web·GraphQL이 거부하는 tenant(공백·줄바꿈·경로 문자)를 받는다. 강화하면 이미 저장된 행을 못 읽을 수 있다. | 남음 | Wave 3 P19 결과 파일 | W3 | 읽기는 관대하게, 새 쓰기만 공용 `TenantId` 문법으로. P30 | | P19-new-2 | 발견 | redis-session 인증 경로(`PrimitiveSessionSecurityContextRepository.java:116`)가 세션에 tenant를 저장하지 않아 JWT 경로와 달리 principal에 tenant가 없다. | 남음 | Wave 3 P19 결과 파일 | W3 | 세션 저장·복원에 tenant 포함. P30 | | P19-new-3 | 발견 | `docs/study/postgresql-jpa-walkthrough.ko.md:818`이 삭제된 `JpaStreamScope`를 설명. | 남음 | Wave 3 P19 결과 파일 | W5 | 결정 6: 현재 코드 기준으로 | +| P28-new-1 | 발견 | fileserver `AtomicMoveContentPublisher`·`ContentPublishVerification`이 보안 walk를 직접 불러 거부를 번역하지 않고 내보냈다. | 완료 | Wave 3 P28 `da49df6c` | - | - | +| ORCH-new-5 | 발견 | P18의 V19가 persistence-jpa `postgresqlMigrationIntegrationTest` 기대값(버전 목록·제약 목록, legacy 미발행 행 삽입)에 반영되지 않았다 — P18 게이트에 이 lane이 없었다. messaging `OutboxPostgresIT`는 P29의 jvm-test-suite 전환 뒤 main 리소스가 jar로 와서 migration 목록을 `File`로 못 읽었다. | 완료 | Wave 3 라운드 3 통합: V19·제약 추가, legacy 행은 PUBLISHED로(V19가 미발행 legacy 행을 거부하는 것이 의도), jar/디렉터리 모두 읽는 목록 조회 — `integrationCheck` 통과 | - | - | diff --git a/docs/study/postgresql-jpa-walkthrough.ko.md b/docs/study/postgresql-jpa-walkthrough.ko.md index f0cc4186..d313dee9 100644 --- a/docs/study/postgresql-jpa-walkthrough.ko.md +++ b/docs/study/postgresql-jpa-walkthrough.ko.md @@ -318,12 +318,12 @@ application-core: + inTransaction(TransactionRequest, Supplier) : TransactionResult adapter: - SpringTransactionPort implements PolicyTransactionPort + SpringTransaction implements PolicyTransactionPort ├─ 레거시 4모드 → 미리 만들어 둔 TransactionTemplate 3개 └─ inTransaction → SpringPolicyTransactionPort (package-private 위임체) ``` -### 3.1 `SpringTransactionPort` — 레거시 4-mode +### 3.1 `SpringTransaction` — 레거시 4-mode 모드별로 `TransactionTemplate`을 **생성 시점에 하나씩 미리 만들어 둔다.** @@ -1627,7 +1627,7 @@ provision하므로 DDL 체크를 건너뛴다. `JdbcLockRegistry(lockRepository, settings.leaseTtl())` — SI 7.0 이후 기본 TTL은 repository setter가 아니라 **registry 생성자**에서 설정한다. -`LockRegistryDistributedLockAdapter`의 계약: +`LockRegistryDistributedLock`의 계약: - **D4 — transaction-commit ordering invariant.** 이 어댑터는 트랜잭션 경계를 관리하지 않는다. 호출자는 보호된 트랜잭션이 **커밋된 뒤에만** 핸들을 release해야 한다. 커밋 전에 release하면 @@ -1670,7 +1670,7 @@ setter가 아니라 **registry 생성자**에서 설정한다. 6. **Spring stereotype 없음** — 두 composition root가 `dev.caskeleton.adapter`를 component-scan하므로 `@Repository`를 붙이면 선택하지 않은 배포에서도 빈이 된다. -### 10.1 `PostgreSqlOwnerSafeIdempotencyStore` +### 10.1 `PostgreSqlIdempotencyStore` `IdempotencyStorePort` 구현. 상태: `CLAIMED → EXECUTING → COMPLETED | FAILED_RETRYABLE | ABANDONED`. @@ -2442,7 +2442,7 @@ audited 엔티티에 대한 `update`가 audit 컬럼을 set하는지 확인한 > 통과와 실패 케이스가 한 번도 실행된 적 없는 아키텍처 규칙은 **모양을 알 수 없는 규칙**이고, > production 그래프에는 오늘 audited bulk update가 없어서 그래프만으로는 통과만 보여줄 수 있다. -`DomainContextAuditContextPort`는 actor를 `DomainContextPropagator`에서 읽고, 빈/blank면 +`DomainContextAuditContext`는 actor를 `DomainContextPropagator`에서 읽고, 빈/blank면 `"system"`으로 떨어뜨린다 — scheduler / Flyway / anonymous 경로에서도 NOT NULL `created_by`/`updated_by`를 항상 만족시키려고. `ACTOR_KEY`를 상수로 격리해서 canonical actor key가 바뀌어도 **정확히 한 클래스**만 손대면 된다. @@ -2690,8 +2690,8 @@ app.fileserver-platform.enabled && transaction-provider != none > 정규식으로 제외하고, 그 제외는 **옳다**: 그게 optional capability를 optional하게 만든다. > > 빠진 건 나머지 절반이다. 이 leaf의 여덟 클래스가 scanned component로 쓰여 있는데 — -> `SpringTransactionPort`, `PersistenceExceptionTranslator`, `StandardSqlStateErrorMapping`, -> `DomainContextAuditContextPort`, idempotency store와 reaper, outbox store와 reaper — +> `SpringTransaction`, `PersistenceExceptionTranslator`, `StandardSqlStateErrorMapping`, +> `DomainContextAuditContext`, idempotency store와 reaper, outbox store와 reaper — > 넓은 scan이 그들에게 도달하기를 멈추자 **아무것도 도달하지 않았다.** `@Component`와 > `@Repository`가 붙어 있고 **돌고 있는 어떤 애플리케이션에서도 빈이 아니었다**: > 특히 `TransactionPort`는 구현이 전혀 없어서, **트랜잭션을 여는 모든 유스케이스가 열 @@ -3296,12 +3296,12 @@ grep -rnE "[0-9]+ ?(개 ?)?-?(leaf|leaves)" docs | grep -v "^docs/superpowers/\| |---|---| | `PostgreSqlIdempotencyStoreConfig` | `@ConditionalOnProperty(ca-skeleton.capabilities.idempotency.provider = postgresql)` | | `IdempotencyReaper` | 동일 | -| `OutboxStoreAdapter` | **없음** (`@Repository`만) | +| `JpaOutboxStore` | **없음** (`@Repository`만) | | `OutboxReaper` | **없음** (`@Component` + `@Scheduled`) | `JpaAdapterComponentsConfig`가 `...persistence.outbox` 패키지를 component scan한다. 따라서 `ca-skeleton.persistence-jpa.enabled=true`이면 `ca-skeleton.outbox.enabled=false`여도 -`OutboxStoreAdapter`와 `OutboxReaper`가 빈이 되고, reaper의 `@Scheduled`가 10분마다 +`JpaOutboxStore`와 `OutboxReaper`가 빈이 되고, reaper의 `@Scheduled`가 10분마다 `delete from outbox_event where status='PUBLISHED' and occurred_at < ?`를 돈다. **확인** @@ -3330,7 +3330,7 @@ V1 `OutboxReaper`의 bulk delete가 매 주기 실패한다.** 지금은 V2가 c 않았지만, cutover 런북에 "V1 reaper/relay 먼저 끄기"가 명시돼야 한다. **제안** -- `OutboxStoreAdapter` / `OutboxReaper`에 `@ConditionalOnProperty(prefix="ca-skeleton.outbox", +- `JpaOutboxStore` / `OutboxReaper`에 `@ConditionalOnProperty(prefix="ca-skeleton.outbox", name="enabled", havingValue="true")` 추가. - cutover 절차에 V1 writer 비활성화 단계를 명시. @@ -3495,7 +3495,7 @@ import하지 않는다** (§11.0 측정). - **`SafeSortMapper.MAX_SORT_TERMS = 4`**: registry에 더 많이 등록할 수 있지만 요청은 4개까지. 의도로 보인다. - **`PgRangeCodec.parse("empty")` 거부**: 의도이고 근거가 적혀 있다. -- **`SpringTransactionPort`의 non-`@Autowired` 생성자들**: 테스트 전용 +- **`SpringTransaction`의 non-`@Autowired` 생성자들**: 테스트 전용 (`withoutAcquisitionEnvelope`). package-private이라 표면이 넓어지지 않는다. --- diff --git a/docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/by_area.cpython-312.pyc b/docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/by_area.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3bd502f9322d28c68ba07b867698e501e637967 GIT binary patch literal 6575 zcmb_geQ*>p_hr!RVOtyUg>4wcIc zX1W-RFdIW%NPDtfEIbV{L!9g4;>Io`qWxUV6gPL75yLWq85=)9E3F9W}IDic$NT93G`Dw3vf8$y%^fp;-HPZQ5T!mhFA2O{?e3KM zkZ{PI98|($VxPNbFhD!1lY{PaUT-WSEAG?2*Bjlw_D0`%+7!X^6D{}XqE32P)m$&8 z5{e+Hb}aPrshENzLB)eq?i8w^r+^L#3#cSVvh?z*_aZE3*L~F z3_f=Cz~0FUbb4hzo{R~qH7>}oMUg~EHTI+;G3;@w$fu&$R8+5`1{F1`=!lA%RCH8D z%_=&kq81e$SJ4R-om5e)%2C}th4-jw-D4>+P{L7Sq{KvtnGy>nR!XRy-?LNVprnA3 zLLeTehn1*VrfYNSB7J;sA5X-T(j#6ZC$!}XNBIPf2@*M#>VZQHw+k|y2|3|!^1=jE zSgIDtlUqu@d}r(rKl^*q-Q#ccclVH_B=$$JAi4K{dHqMkFUbB>GAY6Au>CLxU2EE# zKLr>ECI;ggB)(Vi?%7LH$(YDvas&>lU4SFRFp4Ud_I&NU$jTeosCIl*{yv!IL?qGN z3M0VJnY45DxJVN{wze3wQ-4qIqK8I8?WgJqoT@Aa`virY7JB?EHGfCziBqJz8dOn4 z7(+KSZPzS=oS^mrZFGOrMVgtAc4{mn27Vzx58d?i_PphgqhLh!nh{YMtF=~NN(t`; zc6wy#j-(*T;50%aD0smRL7QWze4x%Ts2_<94)B8{9szBr5fhw}_@0@VWp)t z*AN3uU~+o)=@uUIN$|0nNTLV44cCCqRBtbj`*{$EK^nY*w8lig5QACiI!{R=$cU5r z)^uB06UUpGx;l}= zfI%4Q3Gl?ALa-R;BZ<{MutHH%2$*Jq;sMyWKg{ple}KHk2m8d{UILrXClo@53Q3qK zp@5_4dW2T`8EJF=?SDVh%8Cgar9S*r$;VM?{S!LrQTz#RY$izG zGl|6(KZC7)<{M_U=~_r=(EbfPjwg5ulw6E&V9r-EOgEg)ka5WL{526%eoZnO+eC~( z7QyLo%wVC%c`|Kq*SIBm&S_iKIiI)nyvN&(rLDBVdb07fx2hZO@}v#^ectq|e;U9L zh*Lo&(l0;-M!aYn{!<8#MRT{LEuhjWRfz zqOuT8jd5NHhE-crdu!*Z0FCadF(iqpq-uyjkhH)mS6Xclk|jkRh$vyzBnvz^vTA8* zJbSvey}|D>s|G28RZbBuDk>Kicq| z)L;PN@Sq?jYA9^TN$}X3V3=3Dp`@a@Ke#>MT~NeA4}fw_5U@GnrE7>Numvee@b-Y$ z3kmF11PIr>Lg$23LrwvLCdC0j;~HpAJU8jkkgO)3`KTOCfutr_?+*CO{|RK6S+W<7 z9~?b6(V4YxnDQ;!D~21E9fjjZM~_aNpKZuGJj0EjnH|f{byM4}?wZ~;%U`Kpbb2xt z&$7)iUNu@ZQ8!zfwQV1+|IBO~lPC6FJ~(-Bs_pH%tkeC|ql?bn%g(YH!&Lp%=ILe_ zdpuk2S#<8qSavR%?SJv+_urgI-8OGpuH1ZeaC$J~iDeSf?Mius+-Df8j|G}W+5=wn z0sXhl6-&;w`s=`Lb0xekuiN~9VU6XZ1tZ)@XxUz%DRp`Z-?495Dk=NRmitENy>DV1 z#ScMmCP;~1XpEys`taufhAj*NU{v%zCYpo3Toa=wtx=lkJXQ2QaJ;_;r=t){P2{PP zhghlT8#vg!Lyv7&Xkwz3Xb$@H76xSKyx4%b^-KdZj)H8639{z_2!;?rQ5yE2D*8$% z*|Aa%Kz;}*IYj@kF*^~iiW5^{9x|OcgG}9kkNqcF>(W- znEV~Sj!wU71%JT-4Fqf&#>BvHW$9($R*n8s$D2E(16mzY>j*$hOh{<%rE*a*lJFQ* zjt)>!P&EdHSWK3wDFIYSN9ZVy-dm*Cq52a1%}0Y(gX4lCxy|&Cxffl-tg&bKEbT?>jTKZ``g5EICS-w|d@dxz;kzWw-91 z=NH(_)|WnY)lFTPD7suWS@zDljH_o41X<7s zyvQ)b5tcBkUQ<8}L|ZNRMaj3ULQA%=Nz=`#VKbGjYY*N~`^UXk7;FJfO%n{s z#Cir=Y|vt-W1+=CTi(rm41ihAQJ=~uK>4Idmo#L2rmkzB(A7kY#6Tqw_9FZ=S!^26 zCTIw?(=@W(={A_~h^eCSEOhBn2E> z!%=)-uOsYwCa+zee-iz|^jCoNN)C;PF}g;dGyl|27#IDJ`I}-Lm*Bk9t4Wn%$dcCz zlHDAF=I6lQq!lD)kXo1NoWw%3{nOX@Obv3WIcU3C*ETEFTb0(MUij~W|BLY7uSKkT^u7Qowy5y2U=EC- zje;9zEFTwMp>3iz1(3RG6w{lF`i0~uz16q3y$Mzux`f?!T+f9%#<& zZysi(qtFQx8~TJn)!5P6;XCeeN^Q^xq6cM~2Z#E#z^fXQ65IS@pj0+R@s#hNjRh^SYVf)$nw9 z_QG^u#{24G#jDF}$}gXpJTt{lp8M&R_o}W{&F#6iYXpyQ%Nr`M9DuCB+JQz}Mtma| zCblg(T@wwL2B+F)w_Z8BT(b6Z?PTqgZ}O$t9k)t6%cYRv&!Xw7cUr%IYUk{p=`&Nu zW`lFv=F$6A^DoZV&sAqU2N%k3Y`cj*s=E2&&H5YF8DCpwefynK|9v|Zbl<^Poy(50 z8FSX*9&TJNDSI21fQ;)#%_C@J&j`O{DH!2LEfYnT>=PFjE#+hO`v&O#+_4k5IqS&w z@!g}lC#0-xeTHk9-}dRI+PStV{%UACG|Rsmy|t+pniqEb+WVpRCdwW) z{@&#G-X2=q*?ik|jLQ2i8s(_KWh!nwG#Z-dxzv}j1QynOy7BP5Z^l1cG`r_o>6Nor z1Ji-IwmX|@Zf!ga{U4Wn?7vy`yYkcp`K<4a+m--b?03-@ zj*?5w!;MP?#pB(h-Iv~=63a&r=r-;cbxgGV*h%@yzW{x9jC)7DQ*73@A;U!$QlC~p zCN(3^?w>2VR(oY=HSgMUr*i+Tibml0SpKJdH&eeOza^jidA8+^Y*XNFld#w%WO_r{ zrtobp^5{VUQ*rRo=Nk_{dSGEHk06=)?Z?jY=9g{%cxdY})^T(5)?;RyY6%3WH3b5m zV$~c7z~wOzkp2vKr3et!9)vH`aMOgZb+Tsnng?ii+Hfq=BhhP(bewXU>Gv-9)G4*n zrh}AFB#;hM(nJYOU^T0yLh02w5O{yZ1vRql_plKzZ#LINVy!DT<=|)ePqtN#8Q8`;4>v=*WEo K!>!kV<$nO+@;hMw literal 0 HcmV?d00001 diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index 42f3402b..e6876a06 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -78,7 +78,7 @@ The design gives `web-idempotency` its own `IdempotencyStore`, `IdempotencyRecor `IdempotencyState`, `IdempotencyScope` and `RequestFingerprint`. This repository already has the equivalents in `application-core/idempotency` — `IdempotencyStorePort`, `IdempotencyState`, `IdempotencyScopeDigest` and `RequestFingerprint` — with two provider stores behind the port: -PostgreSQL (`PostgreSqlOwnerSafeIdempotencyStore` in `persistence-jpa`) and Redis +PostgreSQL (`PostgreSqlIdempotencyStore` in `persistence-jpa`) and Redis (`RedisIdempotencyStoreAdapter` in `cache-redis`), selected by `ca-skeleton.capabilities.idempotency.provider`. That is what the design's Tasks 39 and 40 ask for, built in the direction the registry permits. @@ -118,7 +118,7 @@ holding a JPA store for long-running operations, with the port This is the same shape as §6 and takes the same resolution — the one the repository already used for idempotency, where `IdempotencyStorePort` lives in `application-core` and -`PostgreSqlOwnerSafeIdempotencyStore` in `persistence-jpa`: +`PostgreSqlIdempotencyStore` in `persistence-jpa`: | Design type | Here | | --- | --- | diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index fd8ce10b..07400b3a 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -23,6 +23,12 @@ why this rationale lives in Markdown next to the artifact instead of inside it. - realm role `user` — the baseline role the application authorizes ordinary calls on - client role `ca-skeleton-api:graphql-query` — permission to execute a GraphQL query +- client roles `notification-submit`, `notification-template-publish`, `operation-submit` — the + platform permissions `security.yml` maps them to +- client roles `ROLE_FILE_READ` and `ROLE_FILE_WRITE` — the fileserver's read and write tiers, which + `security.yml` also maps to `file:read` and to `file:upload`, `file:delete`, `file:copy`, + `file:move`; `ROLE_FILE_ADMIN` (`file:admin`) is defined but not granted to the service account, + since the management plane is off by default - a service account for the client-credentials grant the qualification lane uses - audience and realm/client role mappers, so the issued token carries what the resource server validates diff --git a/infra/keycloak/realms/ca-skeleton-realm.json b/infra/keycloak/realms/ca-skeleton-realm.json index 1e00633b..a9dd24a2 100644 --- a/infra/keycloak/realms/ca-skeleton-realm.json +++ b/infra/keycloak/realms/ca-skeleton-realm.json @@ -32,6 +32,24 @@ "description": "Submit a durable operation and cancel one's own.", "composite": false, "clientRole": true + }, + { + "name": "ROLE_FILE_READ", + "description": "Fileserver data-plane reads (file:read): metadata, download, upload status, on one's own files. The name is the fileserver's default read tier.", + "composite": false, + "clientRole": true + }, + { + "name": "ROLE_FILE_WRITE", + "description": "Fileserver data-plane writes (file:upload, file:delete, file:copy, file:move) on one's own files. The name is the fileserver's default write tier, so one role satisfies both the permission and the tier check.", + "composite": false, + "clientRole": true + }, + { + "name": "ROLE_FILE_ADMIN", + "description": "Fileserver management plane (file:admin): storage health, orphan reconcile, re-verify, force delete. Not granted to the service account.", + "composite": false, + "clientRole": true } ] } @@ -103,7 +121,9 @@ "graphql-query", "notification-submit", "notification-template-publish", - "operation-submit" + "operation-submit", + "ROLE_FILE_READ", + "ROLE_FILE_WRITE" ] } } diff --git a/src/adapter/inbound/graphql/build.gradle b/src/adapter/inbound/graphql/build.gradle index d5659e61..d71b7210 100644 --- a/src/adapter/inbound/graphql/build.gradle +++ b/src/adapter/inbound/graphql/build.gradle @@ -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 } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminController.java index 7f42dec1..9338f900 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminController.java @@ -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 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 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 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 { *

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); } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java index 57efa748..8b3516b3 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutor.java @@ -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 call(Supplier work) { Future 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", diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java index ddcb7f25..8ff2fa44 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java @@ -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) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java index 811fc818..d7ee6fad 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java @@ -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)); } /** diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java index ab6a8241..74638fc0 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12UploadController.java @@ -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 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())) diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java index 9ec89cf6..11608e65 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java @@ -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 expectedSha256(String ifMatch) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java index 45fd4a63..3089c2f3 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java @@ -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 { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java index 7d263afb..abedadcc 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java @@ -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 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(); } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerTest.java index 007b324e..cb0254fd 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/admin/FileserverAdminControllerTest.java @@ -24,7 +24,7 @@ class FileserverAdminControllerTest { void setUp() { mvc = MockMvcBuilders.standaloneSetup( - new FileserverAdminController(adminService, FileserverWebFixtures.contextFactory())) + adminService.controller(FileserverWebFixtures.contextFactory())) .build(); } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutorSecurityContextTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutorSecurityContextTest.java new file mode 100644 index 00000000..cc99756f --- /dev/null +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/config/BlockingTransferExecutorSecurityContextTest.java @@ -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. + * + *

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(); + } +} diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadControllerContractTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadControllerContractTest.java index fc129544..6099faad 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadControllerContractTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadControllerContractTest.java @@ -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(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java index 501a2963..70ae0c27 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadControllerTest.java @@ -35,7 +35,7 @@ class FileUploadControllerTest { mvc = MockMvcBuilders.standaloneSetup( new FileUploadController( - uploadService, + uploadService.port(), new RawUploadRequestMapper(false), new MultipartUploadRequestMapper(), FileserverWebFixtures.contextFactory(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12ProtocolTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12ProtocolTest.java index e5073518..3c1b31a9 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12ProtocolTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/draft12/Draft12ProtocolTest.java @@ -32,8 +32,9 @@ class Draft12ProtocolTest { mvc = MockMvcBuilders.standaloneSetup( new Draft12UploadController( - uploads, - finalizeService, + uploads.createPort(), + uploads.appendPort(), + finalizeService.port(), FileserverWebFixtures.contextFactory(), FileserverWebFixtures.transferExecutor(), DRAFT)) diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/nginx/NginxDownloadDelegationTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/nginx/NginxDownloadDelegationTest.java index d4420538..f259faec 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/nginx/NginxDownloadDelegationTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/nginx/NginxDownloadDelegationTest.java @@ -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(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverHardeningContractTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverHardeningContractTest.java index 848ace18..94dd0775 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverHardeningContractTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/security/FileserverHardeningContractTest.java @@ -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(), diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java index 5dc39168..12accd51 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java @@ -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 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; + }; + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingAdminService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingAdminService.java index 559f5f45..fdb75424 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingAdminService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingAdminService.java @@ -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 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 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 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); + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingFinalizeService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingFinalizeService.java index 65459595..103fd27c 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingFinalizeService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingFinalizeService.java @@ -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 finalized = new CopyOnWriteArrayList<>(); private final List 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()); + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingUploadService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingUploadService.java index c19d2dcc..775e0d29 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingUploadService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/RecordingUploadService.java @@ -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 receivedBodies = new ArrayList<>(); private final List 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()); + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/StubDownloadService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/StubDownloadService.java index 26056561..db1c06c2 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/StubDownloadService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/StubDownloadService.java @@ -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()); + } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java index b23426bf..491a4293 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java @@ -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(), diff --git a/src/adapter/inbound/web/build.gradle b/src/adapter/inbound/web/build.gradle index 05f46346..f38b936d 100644 --- a/src/adapter/inbound/web/build.gradle +++ b/src/adapter/inbound/web/build.gradle @@ -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. diff --git a/src/adapter/inbound/websocket/build.gradle b/src/adapter/inbound/websocket/build.gradle index a27f1816..541e3d08 100644 --- a/src/adapter/inbound/websocket/build.gradle +++ b/src/adapter/inbound/websocket/build.gradle @@ -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 diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredAdminAuditAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredAdminAudit.java similarity index 94% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredAdminAuditAdapter.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredAdminAudit.java index afec1144..e2279d41 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredAdminAuditAdapter.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredAdminAudit.java @@ -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"); diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredFileserverAuditAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredFileserverAudit.java similarity index 92% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredFileserverAuditAdapter.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredFileserverAudit.java index 4e9094c7..1cca7637 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredFileserverAuditAdapter.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/audit/StructuredFileserverAudit.java @@ -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"); diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java index 0e2ac37b..9c93d01f 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java @@ -43,7 +43,6 @@ import org.springframework.core.env.Environment; FileserverStorageOperationsConfiguration.class, FileserverVerificationConfiguration.class, FileserverSecurityConfiguration.class, - FileserverDownloadLifecycleConfiguration.class, FileserverMaintenanceServiceConfiguration.class }) public class FileserverCapabilityAutoConfiguration { diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverDownloadLifecycleConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverDownloadLifecycleConfiguration.java deleted file mode 100644 index 623edce4..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverDownloadLifecycleConfiguration.java +++ /dev/null @@ -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 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); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverMaintenanceServiceConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverMaintenanceServiceConfiguration.java index b91ee042..6cdc398f 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverMaintenanceServiceConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverMaintenanceServiceConfiguration.java @@ -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. - * - *

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); - } } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecurityConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecurityConfiguration.java index 72f684d8..50135c84 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecurityConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverSecurityConfiguration.java @@ -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) { diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java index b5f0c281..857e76f1 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageGatewayConfiguration.java @@ -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); } } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageOperationsConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageOperationsConfiguration.java index 6fb1df40..d04b8059 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageOperationsConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverStorageOperationsConfiguration.java @@ -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); } } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverVerificationConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverVerificationConfiguration.java index 2ced17a2..a9429e93 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverVerificationConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverVerificationConfiguration.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/RandomUploadIdentifierFactory.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/RandomUploadIdentifier.java similarity index 92% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/RandomUploadIdentifierFactory.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/RandomUploadIdentifier.java index 9f615058..84529c2d 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/RandomUploadIdentifierFactory.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/identifier/RandomUploadIdentifier.java @@ -17,7 +17,7 @@ import java.util.UUID; *

{@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() { diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/AtomicMoveContentPublisher.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/AtomicMoveContentPublisher.java index 4f2d2cfd..beaa2f7a 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/AtomicMoveContentPublisher.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/AtomicMoveContentPublisher.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/ContentPublishVerification.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/ContentPublishVerification.java index f9c351fc..dc06ac70 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/ContentPublishVerification.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/ContentPublishVerification.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCleanupContentGateway.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCleanupContent.java similarity index 89% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCleanupContentGateway.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCleanupContent.java index 44b793f9..18549610 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCleanupContentGateway.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCleanupContent.java @@ -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; } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCopyContentGateway.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCopyContent.java similarity index 93% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCopyContentGateway.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCopyContent.java index 9d464cd7..028fbeaa 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCopyContentGateway.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalCopyContent.java @@ -28,18 +28,17 @@ import java.util.UUID; *

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"); } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScan.java similarity index 98% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScan.java index 12d3c7f7..d73eae10 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapter.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScan.java @@ -39,7 +39,7 @@ import java.util.stream.Stream; *

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, diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalReconciliationContentProbe.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalReconciliationContent.java similarity index 95% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalReconciliationContentProbe.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalReconciliationContent.java index afb36869..16cf018e 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalReconciliationContentProbe.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalReconciliationContent.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageCapabilityProbe.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageCapabilityProbe.java index 53e89c47..39896420 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageCapabilityProbe.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageCapabilityProbe.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailures.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailures.java index 662190f3..4359f583 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailures.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailures.java @@ -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)); + } } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageHealthAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageHealth.java similarity index 95% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageHealthAdapter.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageHealth.java index ee5121e1..ba58e8d7 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageHealthAdapter.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageHealth.java @@ -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) { diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageUsageProbe.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageUsage.java similarity index 92% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageUsageProbe.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageUsage.java index f7599835..3ad1839b 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageUsageProbe.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageUsage.java @@ -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"); } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContentGateway.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java similarity index 97% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContentGateway.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java index e7591770..056d26a1 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContentGateway.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadContent.java @@ -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, diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorage.java similarity index 93% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java rename to src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorage.java index 60ab2076..1f7ccddd 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorage.java @@ -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; } diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SafeFileChannelFactory.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SafeFileChannelFactory.java index b79eca16..5da7d126 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SafeFileChannelFactory.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SafeFileChannelFactory.java @@ -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. * - *

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. + *

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}. * - *

{@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. + *

{@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 OWNER_ONLY_FILE = - PosixFilePermissions.fromString("rw-------"); - private static final Set OWNER_ONLY_DIRECTORY = - PosixFilePermissions.fromString("rwx------"); - - private static final Set CREATE_NEW_OPTIONS = - Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); - private static final Set WRITE_OPTIONS = - Set.of(StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); - private static final Set 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 directory, Path leaf) - throws IOException { - BasicFileAttributes attributes; + /** One filesystem step whose failure is translated into the Fileserver vocabulary. */ + @FunctionalInterface + private interface FileStep { + T run() throws IOException; + } + + private static T translated(FileStep 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 directory, Path leaf) - throws IOException { - return directory - .getFileAttributeView(leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) - .readAttributes(); - } - - private void applyOwnerOnlyPermissions(SecureDirectoryStream 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. - * - *

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 inParent(Path root, Path target, SecureDirectoryWalk.LeafOperation 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", diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FileVerifier.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FileVerifier.java new file mode 100644 index 00000000..3110a90a --- /dev/null +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FileVerifier.java @@ -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. + * + *

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. + * + *

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 verify(VerificationRequest request); +} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FilenamePolicyVerifier.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FilenamePolicyVerifier.java index cae4bf09..ca9f4973 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FilenamePolicyVerifier.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/FilenamePolicyVerifier.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/LengthVerifier.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/LengthVerifier.java index 30fc5c76..56b4dbdc 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/LengthVerifier.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/LengthVerifier.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/MediaTypeVerifier.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/MediaTypeVerifier.java index 995e30a1..5059b6eb 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/MediaTypeVerifier.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/MediaTypeVerifier.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/ScriptableContentPolicy.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/ScriptableContentPolicy.java index 324b35c0..bf9b2c5f 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/ScriptableContentPolicy.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/ScriptableContentPolicy.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/Sha256Verifier.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/Sha256Verifier.java index 3e2a1958..b0cb6482 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/Sha256Verifier.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/Sha256Verifier.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinator.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinator.java index a74179c3..8a588e28 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinator.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinator.java @@ -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; diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapterTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanTest.java similarity index 93% rename from src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapterTest.java rename to src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanTest.java index 81cb0924..a5b5bd5d 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanAdapterTest.java +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalOrphanScanTest.java @@ -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, diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailuresTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailuresTest.java new file mode 100644 index 00000000..c89652f4 --- /dev/null +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageFailuresTest.java @@ -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. + * + *

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); + } +} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java index 5e8c43e5..a053050c 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java @@ -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 diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinatorTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinatorTest.java index 0e94ed3d..4ba55f9a 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinatorTest.java +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/verification/VerificationCoordinatorTest.java @@ -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; diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index 54ab69ca..8b0ebc83 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -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 { diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java index 9097e61b..071eb851 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntime.java @@ -103,6 +103,27 @@ public final class ProviderRuntime { return health.get().reason(); } + /** + * Releases what the adapter holds, when it holds anything. + * + *

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(); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java index 93b652bc..75413b6a 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistry.java @@ -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 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. + * + *

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 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; + } + } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java index 3dd40381..a13d3117 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapter.java @@ -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; diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java index ff8f01e5..dfef6af1 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderRuntimeRegistryTest.java @@ -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() { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java index b2025b4e..809e3084 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesNotificationProviderAdapterTest.java @@ -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 = diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index 75a8c1ac..8fccbb5b 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -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 { diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaMetadataStoreConfig.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaMetadataStoreConfig.java new file mode 100644 index 00000000..58d0de51 --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaMetadataStoreConfig.java @@ -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. + * + *

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); + } +} diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java index f355e71f..0c6950f9 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java @@ -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. * - *

{@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. + *

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 {} diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaQueueStoreConfig.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaQueueStoreConfig.java new file mode 100644 index 00000000..67705c8d --- /dev/null +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaQueueStoreConfig.java @@ -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. + * + *

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); + } +} diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java index 5e1c19f1..b6debb02 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java @@ -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; *

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. */ diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java index 8cbbb8a9..43a8868a 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java @@ -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; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadata.java similarity index 94% rename from src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java rename to src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadata.java index 1b78796c..c9b03b74 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadata.java @@ -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 deletableStates; - public JpaFileMetadataStore( + public JpaFileMetadata( JpaFileRepository files, FileTransitionRepository transitions, Clock clock) { this.files = files; this.transitions = transitions; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java similarity index 88% rename from src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java rename to src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java index b3d41bcd..eb2d7089 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuota.java @@ -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; *

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; } diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommit.java similarity index 92% rename from src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java rename to src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommit.java index 9fdbdb6a..2baaf0c1 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommit.java @@ -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; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaim.java similarity index 84% rename from src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java rename to src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaim.java index 65ea85cf..d0813b01 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaim.java @@ -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; } diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java index 90c49b39..2616bd9c 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java @@ -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"; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java index 0f741ec8..f8f99ded 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java @@ -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); diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSession.java similarity index 94% rename from src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java rename to src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSession.java index 28cec448..b5eeedbd 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSession.java @@ -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; diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 8efb45f1..5f49dc73 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -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` 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 | |---|---|---|---| diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 350fd1d3..bbc806bc 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -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`(그 외 모든 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index af9b37c4..2e4849f3 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -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. diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextPort.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContext.java similarity index 86% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextPort.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContext.java index bc4fd04f..3bd341bc 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextPort.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContext.java @@ -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; } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java index 1dca8fd0..d4fd582a 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java @@ -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); } /** diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java index 3ed431f2..67c9b05b 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java @@ -14,9 +14,9 @@ import org.springframework.context.annotation.FilterType; * beans rather than assembling them and hoping each one remembered to carry the switch. * *

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. diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java similarity index 99% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java index 21302ccd..73431d9c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlOwnerSafeIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java @@ -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); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java index 5f5daea7..f1844f43 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplay.java @@ -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, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java index f25d7139..6859a131 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java @@ -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) { - return new MeteredDistributedLockPort(jdbcDistributedLock, meterRegistry); + return new MeteredDistributedLock(jdbcDistributedLock, meterRegistry); } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java similarity index 94% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockAdapter.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java index 1f5ee101..ce984c7a 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLock.java @@ -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 registry; private final Duration configuredTtl; - public LockRegistryDistributedLockAdapter( + public LockRegistryDistributedLock( LockRegistry registry, Duration configuredTtl) { this.registry = registry; this.configuredTtl = configuredTtl; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPort.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLock.java similarity index 96% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPort.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLock.java index 64283af4..5ea9a23c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPort.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLock.java @@ -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 meterRegistryProvider) { this.delegate = delegate; this.registry = meterRegistryProvider.getIfAvailable(); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java similarity index 97% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java index e4827b96..8c77c318 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStore.java @@ -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)); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java index 12b7ec4c..79d4e4b6 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java @@ -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; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java similarity index 96% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java index 2c89df5d..3f764b5c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransaction.java @@ -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 = diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/LiveEventLogContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/LiveEventLogContractTest.java index 977b9681..d847e9f4 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/LiveEventLogContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/liveevent/LiveEventLogContractTest.java @@ -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()) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java index 92c49366..fa0a4210 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java @@ -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)); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapterContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java similarity index 91% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapterContractTest.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java index 3a840c9e..9cd7d16a 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapterContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java @@ -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); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java index ffe7025d..334d5312 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxIntegrationSupport.java @@ -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, diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java index 5852b65d..e203211e 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java @@ -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) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java index 8656745b..2599b101 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java @@ -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 diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java index a79b0d9b..8cbcffd7 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java @@ -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); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index 6424d3b1..21070929 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -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'"); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java index 8f7bf740..e26623d3 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java @@ -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"); } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index c4d95c48..fa820ddf 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -11,7 +11,7 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaReci import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper; import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.NormalizedEventType; import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; @@ -116,7 +116,7 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { "TRUNCATE notification_provider_event, notification_delivery_attempt," + " notification_recipient_delivery, notification_contact_point, notification_request" + " CASCADE"); - transactions = new SpringTransactionPort(context.getBean(PlatformTransactionManager.class)); + transactions = new SpringTransaction(context.getBean(PlatformTransactionManager.class)); RecipientDeliveryJpaRepository recipients = context.getBean(RecipientDeliveryJpaRepository.class); attempts = diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java index 5b6a0a8c..f2bf2152 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java @@ -3,9 +3,9 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +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.OutboxReaper; -import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.transaction.TransactionPort; @@ -147,7 +147,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { insertStandalone("pending", "PENDING"); // when - Map counts = context.getBean(OutboxStoreAdapter.class).countByStatus(); + Map counts = context.getBean(JpaOutboxStore.class).countByStatus(); // then assertThat(counts).containsExactly(Map.entry(OutboxEventStatus.PENDING, 1L)); @@ -230,7 +230,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { } private List claim() { - OutboxStoreAdapter store = context.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = context.getBean(JpaOutboxStore.class); List leases = context .getBean(TransactionPort.class) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java index ea3c79ae..ae3b56f2 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java @@ -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.outbox.jpa.OutboxStoreAdapter; +import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxRelayResult; @@ -158,12 +158,12 @@ class PostgreSqlOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingC @Override protected OutboxStorePort store() { - return contractContext.getBean(OutboxStoreAdapter.class); + return contractContext.getBean(JpaOutboxStore.class); } @Override protected OutboxAppendPort append() { - return contractContext.getBean(OutboxStoreAdapter.class); + return contractContext.getBean(JpaOutboxStore.class); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java index c636b65e..536e8b39 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxRowLifecycleIntegrationTest.java @@ -2,9 +2,9 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; +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.OutboxReaper; -import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; import dev.caskeleton.application.outbox.OutboxAppendPort; @@ -124,7 +124,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { TransactionPort tx = ctx.getBean(TransactionPort.class); OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class); String eventId = "lifecycle-fail-" + System.nanoTime(); tx.inWrite( @@ -180,7 +180,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { TransactionPort tx = ctx.getBean(TransactionPort.class); OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class); String eventId = "lifecycle-dead-" + System.nanoTime(); tx.inWrite( @@ -375,7 +375,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { TransactionPort tx = ctx.getBean(TransactionPort.class); OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class); String aggId = "agg-fifo-blocked-" + System.nanoTime(); String headId = "fifo-blocked-head-" + System.nanoTime(); @@ -506,7 +506,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { TransactionPort tx = ctx.getBean(TransactionPort.class); OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class); String aggId = "agg-fifo-dead-" + System.nanoTime(); String headId = "fifo-dead-head-" + System.nanoTime(); @@ -582,7 +582,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { TransactionPort tx = ctx.getBean(TransactionPort.class); OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class); String eventId = "lifecycle-orphan-" + System.nanoTime(); tx.inWrite( @@ -640,7 +640,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { TransactionPort tx = ctx.getBean(TransactionPort.class); OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class); - OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class); + JpaOutboxStore store = ctx.getBean(JpaOutboxStore.class); String eventId = "lifecycle-reap-" + System.nanoTime(); String aggId = "agg-reap-" + eventId; @@ -694,7 +694,7 @@ class PostgreSqlOutboxRowLifecycleIntegrationTest { private static PublishPendingOutboxEventsUseCase buildRelayWithClock( AnnotationConfigApplicationContext ctx, Instant clockInstant) { return new PublishPendingOutboxEventsUseCase( - ctx.getBean(OutboxStoreAdapter.class), + ctx.getBean(JpaOutboxStore.class), ctx.getBean(OutboxMessagePublishPort.class), ignored -> {}, ctx.getBean(TransactionPort.class), diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java index 9261edf3..beef27be 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java @@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import java.sql.Connection; @@ -29,7 +29,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; /** - * {@code SpringTransactionPort} against real PostgreSQL. + * {@code SpringTransaction} against real PostgreSQL. * *

The port is plain Spring {@code TransactionTemplate} per mode. What a real database adds over * the unit tests is the part a recording transaction manager cannot show: that a rollback really @@ -71,7 +71,7 @@ class PostgreSqlTransactionIntegrationTest { void inWriteActionFailureRollsBackTheWrite() { // given JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(); + SpringTransaction port = transactionPort(); // when Throwable thrown = @@ -94,7 +94,7 @@ class PostgreSqlTransactionIntegrationTest { void inNewCommitsIndependentlyOfTheCallersRollback() { // given JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(); + SpringTransaction port = transactionPort(); // when Throwable thrown = @@ -146,7 +146,7 @@ class PostgreSqlTransactionIntegrationTest { @Timeout(15) void connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried() throws Exception { JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(); + SpringTransaction port = transactionPort(); AtomicInteger backendPid = new AtomicInteger(); AtomicInteger actionCalls = new AtomicInteger(); try (ExecutorService killer = Executors.newSingleThreadExecutor()) { @@ -196,8 +196,8 @@ class PostgreSqlTransactionIntegrationTest { } } - private static SpringTransactionPort transactionPort() { - return new SpringTransactionPort( + private static SpringTransaction transactionPort() { + return new SpringTransaction( new DataSourceTransactionManager(postgres.dataSource()), translator()); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java index abb0b5fb..57e0d4a6 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java @@ -24,7 +24,7 @@ class CandidateAdapterCompositionTest { void theIdempotencyStoreThatAlreadyFixedThisStaysFixed() { Class store = dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql - .PostgreSqlOwnerSafeIdempotencyStore.class; + .PostgreSqlIdempotencyStore.class; assertThat(store.getAnnotation(Repository.class)) .as("a scan-registered store made both idempotency provider selections fail to start") diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextPortTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextTest.java similarity index 87% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextPortTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextTest.java index 0bcb3e70..1b861bee 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextPortTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/audit/DomainContextAuditContextTest.java @@ -13,10 +13,10 @@ import org.junit.jupiter.api.Test; * Optional.empty()} — the adapter, not the framework, supplies the fallback) and that a bound actor * is read through the runtime-context-propagation seam. */ -class DomainContextAuditContextPortTest { +class DomainContextAuditContextTest { private final DomainContextPropagator propagator = new ThreadLocalDomainContextPropagator(); - private final AuditContextPort port = new DomainContextAuditContextPort(propagator); + private final AuditContextPort port = new DomainContextAuditContext(propagator); @AfterEach void clear() { @@ -31,14 +31,14 @@ class DomainContextAuditContextPortTest { @Test void currentActorReturnsTheBoundActorFromTheRuntimeContextSeam() { - propagator.set(DomainContextAuditContextPort.ACTOR_KEY, "user-42"); + propagator.set(DomainContextAuditContext.ACTOR_KEY, "user-42"); assertThat(port.currentActor()).isEqualTo("user-42"); } @Test void currentActorFallsBackToSystemWhenTheBoundActorIsBlank() { - propagator.set(DomainContextAuditContextPort.ACTOR_KEY, " "); + propagator.set(DomainContextAuditContext.ACTOR_KEY, " "); assertThat(port.currentActor()).isEqualTo("system"); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java index 895c412b..c5d6af8c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java @@ -67,7 +67,7 @@ class PersistenceJpaCapabilityAssemblyTest { assertThat(context.containsBean("jdbcDistributedLock")).isTrue(); assertThat(context.getBean("distributedLockProvider").getClass().getSimpleName()) .as("every caller gets the JDBC provider behind the metrics decorator") - .isEqualTo("MeteredDistributedLockPort"); + .isEqualTo("MeteredDistributedLock"); assertThat(context.getBean(DistributedLockPort.class)) .isSameAs(context.getBean("distributedLockProvider")); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java index 27f00b56..a76b316d 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; 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 org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -25,7 +25,7 @@ class PostgreSqlIdempotencyStoreConfigTest { .run( context -> assertThat(context.getBean(IdempotencyStorePort.class)) - .isInstanceOf(PostgreSqlOwnerSafeIdempotencyStore.class)); + .isInstanceOf(PostgreSqlIdempotencyStore.class)); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java index 3e318d89..9baa4587 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/OwnerSafeIdempotencyPreconditionTest.java @@ -43,8 +43,7 @@ class OwnerSafeIdempotencyPreconditionTest { new IdempotencyScopeDigest("b".repeat(64), 1, "CREATE_WORK_LOG"); private final JdbcOperations jdbc = mock(JdbcOperations.class); - private final PostgreSqlOwnerSafeIdempotencyStore store = - new PostgreSqlOwnerSafeIdempotencyStore(jdbc); + private final PostgreSqlIdempotencyStore store = new PostgreSqlIdempotencyStore(jdbc); @AfterEach void clearTransactionState() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapterActivationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayActivationTest.java similarity index 95% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapterActivationTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayActivationTest.java index 1ecef253..af318cc0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayAdapterActivationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/liveevent/JpaLiveEventReplayActivationTest.java @@ -12,7 +12,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcOperations; -class JpaLiveEventReplayAdapterActivationTest { +class JpaLiveEventReplayActivationTest { private final ApplicationContextRunner runner = new ApplicationContextRunner() @@ -28,7 +28,7 @@ class JpaLiveEventReplayAdapterActivationTest { runner.run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(JpaLiveEventReplayAdapter.class); + assertThat(context).doesNotHaveBean(JpaLiveEventReplay.class); }); } @@ -54,7 +54,7 @@ class JpaLiveEventReplayAdapterActivationTest { .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(JpaLiveEventReplayAdapter.class); + assertThat(context).doesNotHaveBean(JpaLiveEventReplay.class); }); } @@ -67,12 +67,12 @@ class JpaLiveEventReplayAdapterActivationTest { .run( context -> { assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(JpaLiveEventReplayAdapter.class); + assertThat(context).hasSingleBean(JpaLiveEventReplay.class); }); } @Configuration(proxyBeanMethods = false) - @Import(JpaLiveEventReplayAdapter.class) + @Import(JpaLiveEventReplay.class) static class TestConfig { @Bean diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java index 4bdf35d1..412e79e4 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java @@ -46,7 +46,7 @@ class DistributedLockPersistenceConfigTest { .isInstanceOf(DistributedLockPort.class); // Every caller gets the JDBC provider behind the metrics decorator. assertThat(context.getBean("distributedLockProvider")) - .isInstanceOf(MeteredDistributedLockPort.class); + .isInstanceOf(MeteredDistributedLock.class); assertThat(context.getBean(DistributedLockPort.class)) .isSameAs(context.getBean("distributedLockProvider")); }); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java similarity index 89% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockAdapterTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java index e8b06f8b..93c52c49 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockAdapterTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/LockRegistryDistributedLockTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test; import org.springframework.integration.support.locks.DefaultLockRegistry; /** - * Pure unit tests for {@link LockRegistryDistributedLockAdapter} over an in-process {@link + * Pure unit tests for {@link LockRegistryDistributedLock} over an in-process {@link * DefaultLockRegistry} (no database, no Spring context). * *

Determinism strategy

@@ -22,13 +22,13 @@ import org.springframework.integration.support.locks.DefaultLockRegistry; * contending attempt. The background thread releases the lock only after the main thread's * assertion completes. This avoids timing-based sleeps. */ -class LockRegistryDistributedLockAdapterTest { +class LockRegistryDistributedLockTest { private static final Duration CONFIGURED_TTL = Duration.ofSeconds(30); private static final Duration SHORT_WAIT = Duration.ofMillis(50); - private LockRegistryDistributedLockAdapter adapter() { - return new LockRegistryDistributedLockAdapter(new DefaultLockRegistry(), CONFIGURED_TTL); + private LockRegistryDistributedLock adapter() { + return new LockRegistryDistributedLock(new DefaultLockRegistry(), CONFIGURED_TTL); } // ------------------------------------------------------------------ @@ -37,7 +37,7 @@ class LockRegistryDistributedLockAdapterTest { @Test void acquireReturnsNonNullHandle() { - LockRegistryDistributedLockAdapter sut = adapter(); + LockRegistryDistributedLock sut = adapter(); DistributedLock lock = sut.tryAcquire("key-1", SHORT_WAIT, CONFIGURED_TTL); @@ -51,7 +51,7 @@ class LockRegistryDistributedLockAdapterTest { @Test void closeReleasesLockSoReAcquireOnSameKeySucceeds() { - LockRegistryDistributedLockAdapter sut = adapter(); + LockRegistryDistributedLock sut = adapter(); DistributedLock first = sut.tryAcquire("key-2", SHORT_WAIT, CONFIGURED_TTL); first.close(); @@ -73,7 +73,7 @@ class LockRegistryDistributedLockAdapterTest { @Test void timeoutWhenKeyIsHeldByAnotherThreadThrowsWithCorrectKey() throws InterruptedException { - LockRegistryDistributedLockAdapter sut = adapter(); + LockRegistryDistributedLock sut = adapter(); String key = "key-3"; CountDownLatch lockHeld = new CountDownLatch(1); @@ -121,7 +121,7 @@ class LockRegistryDistributedLockAdapterTest { @Test void tryAcquireWithLeaseTtlExceedingConfiguredTtlThrowsIllegalArgumentException() { - LockRegistryDistributedLockAdapter sut = adapter(); // configuredTtl = 30s + LockRegistryDistributedLock sut = adapter(); // configuredTtl = 30s Duration excessiveTtl = CONFIGURED_TTL.plusSeconds(1); // 31s > 30s @@ -135,7 +135,7 @@ class LockRegistryDistributedLockAdapterTest { @Test void handleIsUsableInTryWithResources() { - LockRegistryDistributedLockAdapter sut = adapter(); + LockRegistryDistributedLock sut = adapter(); try (DistributedLock ignored = sut.tryAcquire("key-5", SHORT_WAIT, CONFIGURED_TTL)) { // work diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortLoggingTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockLoggingTest.java similarity index 94% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortLoggingTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockLoggingTest.java index b43b1830..8e430a7e 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortLoggingTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockLoggingTest.java @@ -20,7 +20,7 @@ import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.support.DefaultListableBeanFactory; /** The lease-expiry warning is classified by bounded fields, never by the unbounded lock key. */ -class MeteredDistributedLockPortLoggingTest { +class MeteredDistributedLockLoggingTest { @Test void leaseExpiryWarningCarriesBoundedClassificationWithoutStructuredLockKey() { @@ -30,9 +30,8 @@ class MeteredDistributedLockPortLoggingTest { }; DistributedLockPort delegate = (key, waitTime, leaseTtl) -> expiringHandle; - try (CapturedLogger captured = capture(MeteredDistributedLockPort.class)) { - MeteredDistributedLockPort port = - new MeteredDistributedLockPort(delegate, absentMeterRegistry()); + try (CapturedLogger captured = capture(MeteredDistributedLock.class)) { + MeteredDistributedLock port = new MeteredDistributedLock(delegate, absentMeterRegistry()); DistributedLock lock = port.tryAcquire("customer:unbounded-123", Duration.ofSeconds(1), Duration.ofSeconds(10)); lock.close(); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockTest.java similarity index 78% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockTest.java index cbfdaada..0b58e518 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockTest.java @@ -17,14 +17,14 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.dao.DataAccessResourceFailureException; /** - * Contract test for {@link MeteredDistributedLockPort} (feature-distributed-lock-contract D7 — + * Contract test for {@link MeteredDistributedLock} (feature-distributed-lock-contract D7 — * lock.acquisition counter, tag outcome). * *

Mirrors {@code BackgroundJobMetricsTest}: uses {@code SimpleMeterRegistry} and a real Spring * {@link ObjectProvider} built from a {@link DefaultListableBeanFactory} (including the * absent-registry case). */ -class MeteredDistributedLockPortTest { +class MeteredDistributedLockTest { // ---- acquired path ------------------------------------------------------- @@ -34,8 +34,7 @@ class MeteredDistributedLockPortTest { DistributedLock delegateHandle = () -> {}; DistributedLockPort delegate = (key, waitTime, leaseTtl) -> delegateHandle; - MeteredDistributedLockPort port = - new MeteredDistributedLockPort(delegate, providerOf(registry)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(registry)); DistributedLock handle = port.tryAcquire("test-key", Duration.ofSeconds(1), Duration.ofSeconds(10)); @@ -46,10 +45,8 @@ class MeteredDistributedLockPortTest { assertThatCode(handle::close).doesNotThrowAnyException(); assertThat( registry - .get(MeteredDistributedLockPort.LOCK_ACQUISITION) - .tag( - MeteredDistributedLockPort.TAG_OUTCOME, - MeteredDistributedLockPort.OUTCOME_ACQUIRED) + .get(MeteredDistributedLock.LOCK_ACQUISITION) + .tag(MeteredDistributedLock.TAG_OUTCOME, MeteredDistributedLock.OUTCOME_ACQUIRED) .counter() .count()) .isEqualTo(1.0); @@ -65,8 +62,7 @@ class MeteredDistributedLockPortTest { throw new LockAcquisitionTimeoutException(key, waitTime); }; - MeteredDistributedLockPort port = - new MeteredDistributedLockPort(delegate, providerOf(registry)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(registry)); assertThatThrownBy( () -> port.tryAcquire("test-key", Duration.ofMillis(100), Duration.ofSeconds(10))) @@ -76,10 +72,8 @@ class MeteredDistributedLockPortTest { assertThat( registry - .get(MeteredDistributedLockPort.LOCK_ACQUISITION) - .tag( - MeteredDistributedLockPort.TAG_OUTCOME, - MeteredDistributedLockPort.OUTCOME_TIMEOUT) + .get(MeteredDistributedLock.LOCK_ACQUISITION) + .tag(MeteredDistributedLock.TAG_OUTCOME, MeteredDistributedLock.OUTCOME_TIMEOUT) .counter() .count()) .isEqualTo(1.0); @@ -96,8 +90,7 @@ class MeteredDistributedLockPortTest { throw cause; }; - MeteredDistributedLockPort port = - new MeteredDistributedLockPort(delegate, providerOf(registry)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(registry)); assertThatThrownBy( () -> port.tryAcquire("test-key", Duration.ofSeconds(1), Duration.ofSeconds(10))) @@ -105,10 +98,8 @@ class MeteredDistributedLockPortTest { assertThat( registry - .get(MeteredDistributedLockPort.LOCK_ACQUISITION) - .tag( - MeteredDistributedLockPort.TAG_OUTCOME, - MeteredDistributedLockPort.OUTCOME_ERROR) + .get(MeteredDistributedLock.LOCK_ACQUISITION) + .tag(MeteredDistributedLock.TAG_OUTCOME, MeteredDistributedLock.OUTCOME_ERROR) .counter() .count()) .isEqualTo(1.0); @@ -121,7 +112,7 @@ class MeteredDistributedLockPortTest { DistributedLock delegateHandle = () -> {}; DistributedLockPort delegate = (key, waitTime, leaseTtl) -> delegateHandle; - MeteredDistributedLockPort port = new MeteredDistributedLockPort(delegate, providerOf(null)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(null)); assertThatCode( () -> { @@ -141,7 +132,7 @@ class MeteredDistributedLockPortTest { throw new LockAcquisitionTimeoutException(key, waitTime); }; - MeteredDistributedLockPort port = new MeteredDistributedLockPort(delegate, providerOf(null)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(null)); assertThatThrownBy( () -> port.tryAcquire("test-key", Duration.ofMillis(50), Duration.ofSeconds(10))) @@ -153,9 +144,9 @@ class MeteredDistributedLockPortTest { @Test void outcomeConstantsMatchTheRegistryAllowedValues() { // metrics.yaml lock.acquisition outcome: allowed_values [acquired, timeout, error] - assertThat(MeteredDistributedLockPort.OUTCOME_ACQUIRED).isEqualTo("acquired"); - assertThat(MeteredDistributedLockPort.OUTCOME_TIMEOUT).isEqualTo("timeout"); - assertThat(MeteredDistributedLockPort.OUTCOME_ERROR).isEqualTo("error"); + assertThat(MeteredDistributedLock.OUTCOME_ACQUIRED).isEqualTo("acquired"); + assertThat(MeteredDistributedLock.OUTCOME_TIMEOUT).isEqualTo("timeout"); + assertThat(MeteredDistributedLock.OUTCOME_ERROR).isEqualTo("error"); } // ---- LOCK_LEASE_EXPIRED constant pinned to registry (mirrors outcome pinning) ---- @@ -164,7 +155,7 @@ class MeteredDistributedLockPortTest { void lockLeaseExpiredConstantMatchesRegistryName() { // metrics.yaml has name: lock.lease.expired (tagless counter, feature-distributed-lock-contract // §Edge / D5) - assertThat(MeteredDistributedLockPort.LOCK_LEASE_EXPIRED).isEqualTo("lock.lease.expired"); + assertThat(MeteredDistributedLock.LOCK_LEASE_EXPIRED).isEqualTo("lock.lease.expired"); } // ---- SI-LOCK-C5: lease-expiry on release — ConcurrentModificationException swallowed, metric @@ -180,8 +171,7 @@ class MeteredDistributedLockPortTest { }; DistributedLockPort delegate = (key, waitTime, leaseTtl) -> expiringHandle; - MeteredDistributedLockPort port = - new MeteredDistributedLockPort(delegate, providerOf(registry)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(registry)); DistributedLock handle = port.tryAcquire("test-key", Duration.ofSeconds(1), Duration.ofSeconds(10)); @@ -190,7 +180,7 @@ class MeteredDistributedLockPortTest { assertThatCode(handle::close).doesNotThrowAnyException(); // And the lease-expired counter must have incremented - assertThat(registry.get(MeteredDistributedLockPort.LOCK_LEASE_EXPIRED).counter().count()) + assertThat(registry.get(MeteredDistributedLock.LOCK_LEASE_EXPIRED).counter().count()) .isEqualTo(1.0); } @@ -204,8 +194,7 @@ class MeteredDistributedLockPortTest { }; DistributedLockPort delegate = (key, waitTime, leaseTtl) -> badHandle; - MeteredDistributedLockPort port = - new MeteredDistributedLockPort(delegate, providerOf(registry)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(registry)); DistributedLock handle = port.tryAcquire("test-key", Duration.ofSeconds(1), Duration.ofSeconds(10)); @@ -223,7 +212,7 @@ class MeteredDistributedLockPortTest { }; DistributedLockPort delegate = (key, waitTime, leaseTtl) -> expiringHandle; - MeteredDistributedLockPort port = new MeteredDistributedLockPort(delegate, providerOf(null)); + MeteredDistributedLock port = new MeteredDistributedLock(delegate, providerOf(null)); DistributedLock handle = port.tryAcquire("test-key", Duration.ofSeconds(1), Duration.ofSeconds(10)); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java index 3eb6bb6a..4f3051a2 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java @@ -31,11 +31,16 @@ class AppliedMigrationImmutabilityTest { * ({@code db/migration/jpa/notification-platform}), so a database that applied it still * validates. Its pins stayed in this manifest and are checked where the files now live: moving a * migration must not be the way it stops being frozen. + * + *

The fileserver stream ({@code db/migration/jpa/fileserver}, in {@code + * adapter:outbound:persistence-fileserver}) runs against the same database through the same + * Flyway history and was never pinned at all; it is checked here on the same terms. */ private static final List MIGRATION_ROOTS = List.of( Path.of("src/main/resources/db/migration"), - Path.of("../persistence-notification/src/main/resources/db/migration")); + Path.of("../persistence-notification/src/main/resources/db/migration"), + Path.of("../persistence-fileserver/src/main/resources/db/migration")); private static final Path MANIFEST = Path.of("src/test/resources/db/applied-migrations.sha256"); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java similarity index 97% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java index 5defb0d8..3905930f 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapterTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStoreTest.java @@ -39,8 +39,8 @@ import org.mockito.ArgumentCaptor; import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Unit tests for {@link OutboxStoreAdapter} — covers append mapping, claim transition, mark - * operations, countByStatus, and oldestUnpublishedAgeSecondsByEventType. + * Unit tests for {@link JpaOutboxStore} — covers append mapping, claim transition, mark operations, + * countByStatus, and oldestUnpublishedAgeSecondsByEventType. * *

FIFO gate location contract

* @@ -50,7 +50,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * repository passes through to the caller. Real SKIP LOCKED / FIFO gate behaviour is covered by the * PostgreSQL outbox integration tests. */ -class OutboxStoreAdapterTest { +class JpaOutboxStoreTest { private static final Instant NOW = Instant.parse("2026-06-11T10:00:00Z"); private static final Instant OCCURRED_AT = NOW.minusSeconds(60); @@ -61,7 +61,7 @@ class OutboxStoreAdapterTest { private final OutboxEventJpaRepository repo = mock(OutboxEventJpaRepository.class); private final OutboxClaimRepository claimRepo = mock(OutboxClaimRepository.class); - private final OutboxStoreAdapter adapter = new OutboxStoreAdapter(repo, claimRepo); + private final JpaOutboxStore adapter = new JpaOutboxStore(repo, claimRepo); @BeforeEach void openCallerTransactionBoundary() { @@ -420,11 +420,11 @@ class OutboxStoreAdapterTest { "binding-r1"); } - /** The row {@link OutboxStoreAdapter#append} writes for {@link #event}, still PENDING. */ + /** The row {@link JpaOutboxStore#append} writes for {@link #event}, still PENDING. */ private OutboxEventEntity pendingEntity(String eventId, String aggregateId) { ArgumentCaptor saved = forClass(OutboxEventEntity.class); OutboxEventJpaRepository capture = mock(OutboxEventJpaRepository.class); - new OutboxStoreAdapter(capture, claimRepo).append(event(eventId, aggregateId)); + new JpaOutboxStore(capture, claimRepo).append(event(eventId, aggregateId)); verify(capture).save(saved.capture()); return saved.getValue(); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java index 7f562440..21d0bdbd 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxSwitchWiringContractTest.java @@ -11,7 +11,7 @@ class OutboxSwitchWiringContractTest { @Test void legacyStoreAndReaperRequireTheOutboxSwitch() { - assertOutboxSwitch(OutboxStoreAdapter.class); + assertOutboxSwitch(JpaOutboxStore.class); assertOutboxSwitch(OutboxReaper.class); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceTransactionOwnershipTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceTransactionOwnershipTest.java index b92cca85..1c27595c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceTransactionOwnershipTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceTransactionOwnershipTest.java @@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; -import dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplayAdapter; +import dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplay; import dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository; -import dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationStoreAdapter; +import dev.caskeleton.adapter.outbound.persistence.operation.JpaDurableOperationStore; import dev.caskeleton.application.operation.DurableOperationId; import java.lang.reflect.Method; import java.time.Clock; @@ -23,14 +23,14 @@ class PersistenceTransactionOwnershipTest { @Test void applicationFacingJpaAdaptersDoNotDeclareSpringTransactionBoundaries() { - assertNoTransactionalMethods(DurableOperationStoreAdapter.class); - assertNoTransactionalMethods(JpaLiveEventReplayAdapter.class); + assertNoTransactionalMethods(JpaDurableOperationStore.class); + assertNoTransactionalMethods(JpaLiveEventReplay.class); } @Test void durableOperationMutationRequiresTheCallerTransactionBeforeTouchingTheRepository() { DurableOperationJpaRepository repository = mock(DurableOperationJpaRepository.class); - DurableOperationStoreAdapter adapter = new DurableOperationStoreAdapter(repository); + JpaDurableOperationStore adapter = new JpaDurableOperationStore(repository); assertThatThrownBy( () -> @@ -44,8 +44,8 @@ class PersistenceTransactionOwnershipTest { void liveEventAppendRequiresTheCallerTransactionBeforeAllocatingAPosition() { LiveEventJpaRepository repository = mock(LiveEventJpaRepository.class); JdbcOperations jdbc = mock(JdbcOperations.class); - JpaLiveEventReplayAdapter adapter = - new JpaLiveEventReplayAdapter(repository, jdbc, Clock.systemUTC(), Duration.ofHours(1)); + JpaLiveEventReplay adapter = + new JpaLiveEventReplay(repository, jdbc, Clock.systemUTC(), Duration.ofHours(1)); assertThatThrownBy(() -> adapter.append("stream-1", "{}")) .isInstanceOf(IllegalStateException.class) diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPortTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java similarity index 92% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPortTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java index 19a428ef..a54e7c78 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPortTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionTest.java @@ -18,7 +18,7 @@ import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; -class SpringTransactionPortTest { +class SpringTransactionTest { @AfterEach void clearTransactionState() { @@ -28,7 +28,7 @@ class SpringTransactionPortTest { @Test void inWriteUsesRequiredPropagationReadCommittedIsolationAndNotReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); String result = port.inWrite(() -> "ok"); @@ -47,7 +47,7 @@ class SpringTransactionPortTest { @Test void inReadUsesRequiredPropagationReadCommittedIsolationAndReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); String result = port.inRead(() -> "ok"); @@ -63,7 +63,7 @@ class SpringTransactionPortTest { @Test void inRootWriteUsesRequiredPropagationReadCommittedIsolationAndNotReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); String result = port.inRootWrite(() -> "ok"); @@ -82,7 +82,7 @@ class SpringTransactionPortTest { @Test void inRootWriteRejectsAmbientActualTransactionBeforeActionOrTransactionManagerSideEffects() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); AtomicBoolean actionCalled = new AtomicBoolean(); TransactionSynchronizationManager.setActualTransactionActive(true); @@ -104,7 +104,7 @@ class SpringTransactionPortTest { @Test void inRootWriteReturnsOnlyAfterPhysicalCommitCompletes() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); String result = port.inRootWrite( @@ -122,7 +122,7 @@ class SpringTransactionPortTest { void inRootWritePropagatesCommitFailureWithoutPublishingCallerVisibleResult() { RecordingTransactionManager tm = new RecordingTransactionManager(); tm.failCommit = true; - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); AtomicReference callerVisible = new AtomicReference<>(); assertThatThrownBy( @@ -145,7 +145,7 @@ class SpringTransactionPortTest { @Test void inNewUsesRequiresNewPropagationReadCommittedIsolationAndNotReadOnly() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); port.inNew(() -> null); @@ -164,7 +164,7 @@ class SpringTransactionPortTest { void inNewBoundsItsTransactionToThirtySeconds() { // given RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); // when port.inNew(() -> "ok"); @@ -176,7 +176,7 @@ class SpringTransactionPortTest { @Test void everyModePinsAnExplicitIsolationNeverTheVendorDefault() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); port.inWrite(() -> null); port.inRead(() -> null); @@ -197,7 +197,7 @@ class SpringTransactionPortTest { @Test void exceptionInsideActionTriggersRollback() { RecordingTransactionManager tm = new RecordingTransactionManager(); - SpringTransactionPort port = new SpringTransactionPort(tm); + SpringTransaction port = new SpringTransaction(tm); IllegalStateException thrown = catchAndReturn( diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 index 543067e0..e32cb6f7 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -3,6 +3,11 @@ # Add a line when adding a migration; change a line only for a file no database can have applied. 741916fa569f4d90c20cad3f9c1e1a4aab70971f72265f4713b9710fa9db9a10 jpa/core/V1__initialize_or_adopt.sql 18dd16fe7f7cc902da8947b5ce830b06d6cd7833ba2d431e72105d6f7fce6021 jpa/core/V2__widen_capability_schema_stream.sql +1ecab868867cd5faba444b0ed20c1d2e5f42bd27afbd985ab37a7c97487d7dfc jpa/fileserver/V1__create_fileserver_metadata.sql +248202d9608fa4351af8146791366ee2cfd0d9aa00c9897d7e94c0f2c20d722a jpa/fileserver/V2__fileserver_recovery_and_staging_cleanup.sql +0998c73054e2781937fa6ba4710b329353d60253b3a5b475ea7c3c2bac92cc9f jpa/fileserver/V3__fileserver_fenced_cleanup_lease.sql +04962da5aea6dd5456ee4c53f33ee5b4c86c57a617a856b9ff597cab0e65f94b jpa/fileserver/V4__fileserver_upload_terminal_state.sql +92b43496e6eb2d7c1a256ddfc0d3c3a6d9a25141e4a9223a00ed456c0a42deee jpa/fileserver/V5__fileserver_file_owner.sql 2ba4214941a5563613b0dcc4f7cbf5f1278e342b900268721466e4bdeaa2fef2 jpa/idempotency/V1__expand_owner_safe_v2.sql 95be788589f01e32c9179acc80817e227e81805f8d518e8a9ac36e1c31b51da7 jpa/idempotency/V2__request_hash_varchar.sql 4379872989af0c97b937ff48527c788a2ba0216218d4df9435eba8c6e053ad8d jpa/notification-platform/V10__variables_payload_envelope_guard.sql diff --git a/src/adapter/outbound/persistence-mongo/build.gradle b/src/adapter/outbound/persistence-mongo/build.gradle index 6f9fde10..24aa7e4b 100644 --- a/src/adapter/outbound/persistence-mongo/build.gradle +++ b/src/adapter/outbound/persistence-mongo/build.gradle @@ -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' } @@ -55,30 +54,53 @@ dependencies { // // `java-test-fixtures` creates the source set and puts it on `test`'s classpath itself, so neither a // `sourceSet('testFixtures')` declaration nor a `testFixturesPublisher { consumedBy 'test' }` is needed. -// The performance lane is not `test` and still has to say it consumes the fixtures, which is what -// `compilesAgainst` is for — it looks a source set up rather than creating one, so naming a -// plugin-created set works unchanged. +// The provider lanes are not `test` and still have to say they consume the fixtures, which is the +// `implementation testFixtures(project())` line in each suite below. // // What is given up: the convention's opt-in publishing. This leaf's fixtures are now a consumable // variant whether or not anybody asks for them. ADR-BUILD-001 records that as an accepted loss — // unconsumed fixtures are unconsumed, and a leaf that genuinely must not offer them needs a module, // not a third convention. -auxiliarySourceSets { - // Provider fixtures are isolated from java-test-fixtures so ordinary unit tests never acquire - // Testcontainers just because a provider lane exists in this leaf. - sourceSet('mongoProviderTestkit') { - compilesAgainst 'main', 'testFixtures' - inherits 'implementation', 'runtimeOnly' + +// Provider fixtures are isolated from java-test-fixtures so ordinary unit tests never acquire +// Testcontainers just because a provider lane exists in this leaf. They are a plain source set, not +// a test suite: they hold no tests, only what the two lanes below compile against. +sourceSets { + mongoProviderTestkit { + compileClasspath += main.output + testFixtures.output + runtimeClasspath += main.output + testFixtures.output } - sourceSet('mongoIntegrationTest') { - compilesAgainst 'main', 'testFixtures', 'mongoProviderTestkit' - inherits 'implementation', 'runtimeOnly' +} +testing { + suites { + mongoIntegrationTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project()) + } + } + mongoPerformanceTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project()) + } + } } - sourceSet('mongoPerformanceTest') { - compilesAgainst 'main', 'testFixtures', 'mongoProviderTestkit' - inherits 'implementation', 'runtimeOnly' +} +['mongoIntegrationTest', 'mongoPerformanceTest'].each { name -> + sourceSets.named(name) { + compileClasspath += sourceSets.mongoProviderTestkit.output + runtimeClasspath += sourceSets.mongoProviderTestkit.output } } +configurations { + mongoProviderTestkitImplementation.extendsFrom testImplementation + mongoProviderTestkitRuntimeOnly.extendsFrom testRuntimeOnly + mongoIntegrationTestImplementation.extendsFrom testImplementation + mongoIntegrationTestRuntimeOnly.extendsFrom testRuntimeOnly + mongoPerformanceTestImplementation.extendsFrom testImplementation + mongoPerformanceTestRuntimeOnly.extendsFrom testRuntimeOnly +} // The fixtures declare what they compile against, rather than inheriting the test configuration. // diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md index 7a2a8f40..4aa8050e 100644 --- a/src/adapter/outbound/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/README.md @@ -14,10 +14,11 @@ In the service's own outbound adapter leaf — never in `domain-core` or `applic ```groovy implementation project(':adapter:outbound:redis-sdk') -implementation project(':adapter:outbound:redis-runtime') // RedisRuntimeOwner, RedisLaneContribution ``` -and register both edges in that leaf's `allowed_dependencies` in +`redis-runtime` comes with it: the SDK's public types extend and return runtime types +(`SemanticRedisCommands`, `RedisLaneContribution`, …), so the SDK declares the runtime as `api`. +Register both edges in that leaf's `allowed_dependencies` in `src/config/architecture/modules.json` (HARD-STOP 5). Put the adapter behind an application-core port, as for any other outbound capability. diff --git a/src/adapter/outbound/redis-sdk/build.gradle b/src/adapter/outbound/redis-sdk/build.gradle index d13ae0e2..b30b8558 100644 --- a/src/adapter/outbound/redis-sdk/build.gradle +++ b/src/adapter/outbound/redis-sdk/build.gradle @@ -1,12 +1,16 @@ plugins { id 'ca.spring-library' + // `java-library` for the `api` configuration: the SDK's public types extend and return + // redis-runtime types (SemanticRedisCommands, WritePresence, RedisLaneContribution, + // RedisDriverConnection), so a consumer cannot compile against the SDK without the runtime. + id 'java-library' id 'ca.redis-topology-lane' } description = 'Optional typed Redis SDK library: guarded typed operations, admin/raw surfaces and extensions' dependencies { - implementation project(':adapter:outbound:redis-runtime') + api project(':adapter:outbound:redis-runtime') implementation 'org.springframework:spring-core' implementation 'io.lettuce:lettuce-core' implementation 'io.projectreactor:reactor-core' diff --git a/src/adapter/outbound/support/CLAUDE.md b/src/adapter/outbound/support/CLAUDE.md index 82d6f0b6..150f45d9 100644 --- a/src/adapter/outbound/support/CLAUDE.md +++ b/src/adapter/outbound/support/CLAUDE.md @@ -20,6 +20,11 @@ Package roots: `dev.caskeleton.adapter.outbound` and backing off to a service's own encoder). It lives here because a use case encodes before it appends to the outbox, in compositions that carry no messaging module; it is the application's own envelope v1 format, not an external-system protocol. +- Own the descriptor-relative local filesystem primitive (`filesystem/SecureDirectoryWalk`, + `filesystem/SecureFileAccess`): open, create, delete, stat and move below a root one directory + descriptor at a time with `NOFOLLOW_LINKS`, refusing symbolic components and escapes with typed + `IOException`s. A storage capability translates those into its own failure vocabulary (the + Fileserver's `LocalStorageFailures`); nothing here knows an error code. - Keep feature-specific clients and routing policies in their owning leaf. ## Boundaries diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SecureDirectoryWalk.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureDirectoryWalk.java similarity index 88% rename from src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SecureDirectoryWalk.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureDirectoryWalk.java index 59512656..effe2c46 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SecureDirectoryWalk.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureDirectoryWalk.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.fileserver.platform.local; +package dev.caskeleton.adapter.outbound.support.filesystem; import java.io.IOException; import java.nio.file.DirectoryStream; @@ -31,18 +31,18 @@ import java.util.Deque; * the capability probe rather than as a reason to fall back, because a silent fall back to * pathnames would restore exactly the window this class exists to close. */ -final class SecureDirectoryWalk { +public final class SecureDirectoryWalk { private SecureDirectoryWalk() {} /** What to do once the walk is standing in the leaf's parent directory. */ @FunctionalInterface - interface DirectoryOperation { + public interface DirectoryOperation { T apply(SecureDirectoryStream directory) throws IOException; } @FunctionalInterface - interface LeafOperation { + public interface LeafOperation { /** * Runs the operation against an already-verified parent directory. @@ -59,10 +59,11 @@ final class SecureDirectoryWalk { *

{@code target} must be inside {@code root}; the caller's path resolver has already proven * that, and this re-derives the relative segments rather than trusting a prefix comparison. */ - static T inParentOf(Path root, Path target, LeafOperation operation) throws IOException { + public static T inParentOf(Path root, Path target, LeafOperation operation) + throws IOException { Path relative = relativeBelow(root, target); if (relative.getNameCount() == 0) { - throw new IOException("secure walk target must be below the storage root"); + throw new PathEscapeException("secure walk target must be below the storage root"); } Path leafName = relative.getFileName(); Deque> open = new ArrayDeque<>(); @@ -81,7 +82,7 @@ final class SecureDirectoryWalk { } /** Runs an operation against an exact directory reached only through verified descriptors. */ - static T inDirectory(Path root, Path directory, DirectoryOperation operation) + public static T inDirectory(Path root, Path directory, DirectoryOperation operation) throws IOException { Path relative = relativeBelow(root, directory); Deque> open = new ArrayDeque<>(); @@ -105,11 +106,11 @@ final class SecureDirectoryWalk { * the source nor target parent is resolved by pathname after validation, so replacing a checked * directory component with a symlink cannot redirect the rename. */ - static void move(Path root, Path source, Path target) throws IOException { + public static void move(Path root, Path source, Path target) throws IOException { Path sourceRelative = relativeBelow(root, source); Path targetRelative = relativeBelow(root, target); if (sourceRelative.getNameCount() == 0 || targetRelative.getNameCount() == 0) { - throw new IOException("secure move endpoints must be below the storage root"); + throw new PathEscapeException("secure move endpoints must be below the storage root"); } Deque> open = new ArrayDeque<>(); @@ -141,7 +142,7 @@ final class SecureDirectoryWalk { Path normalizedRoot = root.toAbsolutePath().normalize(); Path normalizedTarget = target.toAbsolutePath().normalize(); if (!normalizedTarget.startsWith(normalizedRoot)) { - throw new IOException("secure walk target must stay below the storage root"); + throw new PathEscapeException("secure walk target must stay below the storage root"); } return normalizedRoot.relativize(normalizedTarget); } @@ -179,7 +180,7 @@ final class SecureDirectoryWalk { } /** A path component below the storage root is a symbolic link; a permanent rejection. */ - static final class SymbolicComponentException extends IOException { + public static final class SymbolicComponentException extends IOException { private static final long serialVersionUID = 1L; @@ -188,6 +189,19 @@ final class SecureDirectoryWalk { } } + /** + * A target that does not lie strictly below the root: {@code ..}, an absolute path elsewhere, or + * the root itself. A permanent rejection, like a symbolic component, and not an I/O outage. + */ + public static final class PathEscapeException extends IOException { + + private static final long serialVersionUID = 1L; + + PathEscapeException(String message) { + super(message); + } + } + /** * Opens the root itself as a secure stream. * @@ -213,7 +227,7 @@ final class SecureDirectoryWalk { } /** True when the platform can do descriptor-relative access at all; used by the startup probe. */ - static boolean isSupported(Path directory) { + public static boolean isSupported(Path directory) { try (DirectoryStream stream = Files.newDirectoryStream(directory)) { return stream instanceof SecureDirectoryStream; } catch (IOException unsupported) { diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccess.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccess.java new file mode 100644 index 00000000..7b7fca02 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccess.java @@ -0,0 +1,273 @@ +package dev.caskeleton.adapter.outbound.support.filesystem; + +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, creates, deletes and inspects local files through directory descriptors, never through a + * re-resolved pathname. + * + *

Proving that no component below a root is a symbolic link and then calling {@code + * FileChannel.open} on the full path 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 operation here instead descends one directory at a time with {@code + * NOFOLLOW_LINKS} ({@link SecureDirectoryWalk}) and acts relative to the innermost descriptor, so + * what was verified and what is used are the same object. + * + *

The refusals are typed and stay {@link IOException}s, so each storage capability keeps its own + * failure vocabulary: {@link SecureDirectoryWalk.SymbolicComponentException} for a symbolic link + * anywhere on the way, the leaf included; {@link SecureDirectoryWalk.PathEscapeException} for a + * target that is not strictly below the root; {@link NotRegularFileException} for a leaf that is a + * directory or a device. None of them is an outage, and a caller must not retry one. + * + *

Files are created owner-read-write only and directories owner-only; a storage root is private + * to the process that serves it. + */ +public final class SecureFileAccess { + + private static final Set OWNER_ONLY_FILE = + PosixFilePermissions.fromString("rw-------"); + private static final Set OWNER_ONLY_DIRECTORY = + PosixFilePermissions.fromString("rwx------"); + + private static final Set CREATE_NEW_OPTIONS = + Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); + private static final Set WRITE_OPTIONS = + Set.of(StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); + private static final Set READ_OPTIONS = + Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + + private SecureFileAccess() {} + + /** + * Creates a brand-new zero-length file; an existing target is a conflict, never an overwrite. + * + * @param root the storage root + * @param target the file, strictly below {@code root} + * @return an open channel positioned at zero + * @throws java.nio.file.FileAlreadyExistsException when anything already has that name + * @throws IOException on a refusal or a filesystem failure + */ + public static FileChannel createNew(Path root, Path target) throws IOException { + createParentDirectories(root, target); + return SecureDirectoryWalk.inParentOf( + 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. + try { + applyOwnerOnlyPermissions(directory, leaf); + requireRegularFile(directory, leaf); + return channel; + } catch (IOException | RuntimeException failure) { + closeQuietly(channel); + throw failure; + } + }); + } + + /** + * Opens an existing regular file for writing. + * + * @param root the storage root + * @param target the file, strictly below {@code root} + * @return an open channel + * @throws IOException on a refusal, absence or a filesystem failure + */ + public static FileChannel openForWrite(Path root, Path target) throws IOException { + return SecureDirectoryWalk.inParentOf( + root, + target, + (directory, leaf) -> { + requireRegularFile(directory, leaf); + return requireFileChannel(directory.newByteChannel(leaf, WRITE_OPTIONS)); + }); + } + + /** + * Opens an existing regular file for reading. + * + * @param root the storage root + * @param target the file, strictly below {@code root} + * @return an open channel + * @throws NoSuchFileException when nothing has that name + * @throws IOException on a refusal or a filesystem failure + */ + public static FileChannel openForRead(Path root, Path target) throws IOException { + return SecureDirectoryWalk.inParentOf( + root, + target, + (directory, leaf) -> { + requireRegularFile(directory, leaf); + return requireFileChannel(directory.newByteChannel(leaf, READ_OPTIONS)); + }); + } + + /** + * Deletes a regular file relative to its verified parent. + * + * @param root the storage root + * @param target the file, strictly below {@code root} + * @return true when this call deleted it, false when it was already gone + * @throws IOException on a refusal or a filesystem failure + */ + public static boolean deleteRegularFile(Path root, Path target) throws IOException { + return SecureDirectoryWalk.inParentOf( + root, + target, + (directory, leaf) -> { + try { + requireRegularFile(directory, leaf); + directory.deleteFile(leaf); + return true; + } catch (NoSuchFileException alreadyGone) { + return false; + } + }); + } + + /** + * Reads a leaf's attributes without following a link. + * + * @param root the storage root + * @param target the leaf, strictly below {@code root} + * @return the attributes of the object itself + * @throws NoSuchFileException when nothing has that name + * @throws IOException on a refusal or a filesystem failure + */ + public static BasicFileAttributes readAttributes(Path root, Path target) throws IOException { + return SecureDirectoryWalk.inParentOf(root, target, SecureFileAccess::attributesOf); + } + + /** + * True when a regular, non-symbolic file has that name. + * + * @param root the storage root + * @param target the leaf, strictly below {@code root} + * @return whether a regular file is there + * @throws IOException when a component on the way is refused, or on a filesystem failure + */ + public static boolean isRegularFile(Path root, Path target) throws IOException { + try { + return readAttributes(root, target).isRegularFile(); + } catch (NoSuchFileException absent) { + return false; + } + } + + /** + * Creates the missing directories above {@code target}, owner-only. + * + *

Pathname-based, like every directory creation the JDK offers; what makes it safe is that + * nothing is ever opened through the path this creates. A component swapped for a link + * afterwards is refused by the descriptor walk that every other operation takes. + * + * @param root the storage root + * @param target a leaf strictly below {@code root} + * @throws IOException on a filesystem failure + */ + public static void createParentDirectories(Path root, Path target) throws IOException { + Path parent = target.getParent(); + if (parent == null || Files.isDirectory(parent, LinkOption.NOFOLLOW_LINKS)) { + return; + } + Files.createDirectories(parent); + if (!parent.getFileSystem().supportedFileAttributeViews().contains("posix")) { + return; + } + Path current = root.toAbsolutePath().normalize(); + for (Path segment : current.relativize(parent.toAbsolutePath().normalize())) { + current = current.resolve(segment); + Files.setPosixFilePermissions(current, OWNER_ONLY_DIRECTORY); + } + } + + /** Type check through the parent descriptor, so it names the object that was opened. */ + private static void requireRegularFile(SecureDirectoryStream directory, Path leaf) + throws IOException { + BasicFileAttributes attributes; + try { + attributes = attributesOf(directory, leaf); + } catch (NoSuchFileException absent) { + return; + } + if (attributes.isSymbolicLink()) { + throw new SecureDirectoryWalk.SymbolicComponentException(); + } + if (!attributes.isRegularFile()) { + throw new NotRegularFileException(); + } + } + + private static BasicFileAttributes attributesOf(SecureDirectoryStream directory, Path leaf) + throws IOException { + return directory + .getFileAttributeView(leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) + .readAttributes(); + } + + private static void applyOwnerOnlyPermissions(SecureDirectoryStream directory, Path leaf) + throws IOException { + PosixFileAttributeView view = + directory.getFileAttributeView( + leaf, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); + if (view == null) { + return; + } + view.setPermissions(OWNER_ONLY_FILE); + } + + /** + * The caller needs a {@link FileChannel}, not any seekable channel. + * + *

Positional reads, {@code truncate}, {@code force} and {@code transferTo} are all {@code + * FileChannel} operations. Every platform that offers {@link SecureDirectoryStream} returns one; + * a platform that did not would have to be refused rather than silently degraded. + */ + 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"); + } + + 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. + } + } + + /** The leaf exists and is neither a regular file nor a link: a directory, a device, a pipe. */ + public static final class NotRegularFileException extends IOException { + + private static final long serialVersionUID = 1L; + + NotRegularFileException() { + super("storage target is not a regular file"); + } + } +} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SecureDirectoryWalkTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureDirectoryWalkTest.java similarity index 96% rename from src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SecureDirectoryWalkTest.java rename to src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureDirectoryWalkTest.java index d61f4a24..17bae773 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/SecureDirectoryWalkTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureDirectoryWalkTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.fileserver.platform.local; +package dev.caskeleton.adapter.outbound.support.filesystem; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccessTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccessTest.java new file mode 100644 index 00000000..b2fb8222 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/filesystem/SecureFileAccessTest.java @@ -0,0 +1,170 @@ +package dev.caskeleton.adapter.outbound.support.filesystem; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class SecureFileAccessTest { + + @TempDir Path sandbox; + + private Path root; + private Path outside; + + @BeforeEach + void layOutARootAndSomethingOutsideIt() throws IOException { + org.junit.jupiter.api.Assumptions.assumeTrue(SecureDirectoryWalk.isSupported(sandbox)); + root = Files.createDirectory(sandbox.resolve("root")); + outside = Files.createDirectory(sandbox.resolve("outside")); + Files.writeString(outside.resolve("secret"), "not yours"); + } + + @Test + void aFileCreatedAndWrittenIsReadBackThroughDescriptors() throws IOException { + // given + Path target = root.resolve("a/b/object"); + try (FileChannel written = SecureFileAccess.createNew(root, target)) { + written.write(ByteBuffer.wrap("payload".getBytes(StandardCharsets.UTF_8))); + } + + // when + String read; + try (FileChannel channel = SecureFileAccess.openForRead(root, target)) { + ByteBuffer buffer = ByteBuffer.allocate(16); + channel.read(buffer); + read = new String(buffer.array(), 0, buffer.position(), StandardCharsets.UTF_8); + } + + // then + assertThat(read).isEqualTo("payload"); + } + + @Test + void aSecondCreateOfTheSameNameIsAConflictNotAnOverwrite() throws IOException { + // given + Path target = root.resolve("object"); + SecureFileAccess.createNew(root, target).close(); + + // when + Throwable thrown = catchThrowable(() -> SecureFileAccess.createNew(root, target)); + + // then + assertThat(thrown).isInstanceOf(FileAlreadyExistsException.class); + } + + @Test + void aLeafThatIsASymbolicLinkIsNeverOpened() throws IOException { + // given + Files.createSymbolicLink(root.resolve("leak"), outside.resolve("secret")); + + // when + Throwable thrown = + catchThrowable(() -> SecureFileAccess.openForRead(root, root.resolve("leak"))); + + // then + assertThat(thrown) + .isInstanceOf(SecureDirectoryWalk.SymbolicComponentException.class) + .hasMessage("a storage path component is a symbolic link"); + } + + @Test + void aDirectoryComponentThatIsASymbolicLinkIsNeverDescended() throws IOException { + // given + Files.createSymbolicLink(root.resolve("dir"), outside); + + // when + Throwable thrown = + catchThrowable(() -> SecureFileAccess.openForRead(root, root.resolve("dir/secret"))); + + // then + assertThat(thrown) + .isInstanceOf(SecureDirectoryWalk.SymbolicComponentException.class) + .hasMessage("a storage path component is a symbolic link"); + } + + @Test + void aTargetThatClimbsOutOfTheRootIsRefusedBeforeAnythingIsOpened() { + // when + Throwable thrown = + catchThrowable(() -> SecureFileAccess.openForRead(root, root.resolve("../outside/secret"))); + + // then + assertThat(thrown) + .isInstanceOf(SecureDirectoryWalk.PathEscapeException.class) + .hasMessage("secure walk target must stay below the storage root"); + } + + @Test + void aDeleteThroughASymbolicLeafRemovesNeitherTheLinkTargetNorTheLink() throws IOException { + // given + Path link = Files.createSymbolicLink(root.resolve("leak"), outside.resolve("secret")); + + // when + Throwable thrown = catchThrowable(() -> SecureFileAccess.deleteRegularFile(root, link)); + + // then + assertThat( + List.of( + thrown.getClass(), + Files.exists(outside.resolve("secret")), + Files.isSymbolicLink(link))) + .containsExactly(SecureDirectoryWalk.SymbolicComponentException.class, true, true); + } + + @Test + void aLeafThatIsADirectoryIsRefusedAsNotARegularFile() throws IOException { + // given + Files.createDirectory(root.resolve("folder")); + + // when + Throwable thrown = + catchThrowable(() -> SecureFileAccess.openForRead(root, root.resolve("folder"))); + + // then + assertThat(thrown) + .isInstanceOf(SecureFileAccess.NotRegularFileException.class) + .hasMessage("storage target is not a regular file"); + } + + /** + * The race the descriptor walk exists for: a directory verified and opened, then swapped for a + * link before the leaf is used. The operation still acts on the directory it opened. + */ + @Test + void aDirectorySwappedForALinkAfterItWasOpenedDoesNotRedirectTheOperation() throws IOException { + // given + Path directory = Files.createDirectory(root.resolve("dir")); + Files.writeString(directory.resolve("object"), "inside"); + Path moved = sandbox.resolve("moved-away"); + + // when + String read = + SecureDirectoryWalk.inParentOf( + root, + root.resolve("dir/object"), + (parent, leaf) -> { + // The attacker's swap, between the walk's verification and the use of the leaf. + Files.move(directory, moved); + Files.createSymbolicLink(directory, outside); + try (var channel = parent.newByteChannel(leaf, java.util.Set.of())) { + ByteBuffer buffer = ByteBuffer.allocate(16); + channel.read(buffer); + return new String(buffer.array(), 0, buffer.position(), StandardCharsets.UTF_8); + } + }); + + // then + assertThat(read).isEqualTo("inside"); + } +} diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index d2d91f34..9b8dca31 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -3,7 +3,6 @@ plugins { id 'ca.spring-config' id 'org.springframework.boot' id 'ca.config-contract' - id 'ca.auxiliary-source-set' id 'ca.bootrun-dotenv' } @@ -15,21 +14,40 @@ plugins { // feedback loop starts a database is a leaf nobody runs the fast loop on. This is the same shape // persistence-jpa, web, websocket and objectstorage already use, declared through the repository's // own strictTestLanes DSL rather than by hand. -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' - inherits 'implementation', 'compileOnly', 'runtimeOnly', 'annotationProcessor' +// The suites see main (and two of them the test classes) as class directories rather than through +// `implementation project()`: this is a Spring Boot application project, and its lanes have always +// run on main's output, not on the plain jar. +testing { + suites { + integrationTest(JvmTestSuite) + architectureTest(JvmTestSuite) + // No test runtime and no inherited test dependencies: the full-boot lane runs on the + // composition bootJar packages (see the configurations block below). + systemTest(JvmTestSuite) } - sourceSet('architectureTest') { - compilesAgainst 'main', 'test' - inherits 'implementation', 'compileOnly', 'runtimeOnly', 'annotationProcessor' - runtimeFrom 'test' +} +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestCompileOnly.extendsFrom testCompileOnly + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly + integrationTestAnnotationProcessor.extendsFrom testAnnotationProcessor + architectureTestImplementation.extendsFrom testImplementation + architectureTestCompileOnly.extendsFrom testCompileOnly + architectureTestRuntimeOnly.extendsFrom testRuntimeOnly + architectureTestAnnotationProcessor.extendsFrom testAnnotationProcessor + systemTestAnnotationProcessor.extendsFrom testAnnotationProcessor +} +sourceSets { + integrationTest { + compileClasspath += main.output + runtimeClasspath += main.output } - // No `runtimeFrom 'test'` and no inherited test dependencies: the full-boot lane runs on the - // composition bootJar packages (see the configurations block below). - sourceSet('systemTest') { - compilesAgainst 'main', 'test' - inherits 'annotationProcessor' + architectureTest { + compileClasspath += main.output + test.output + } + systemTest { + compileClasspath += main.output + test.output + runtimeClasspath += main.output + test.output } } @@ -73,10 +91,12 @@ tasks.named('check') { dependsOn tasks.named('systemTestLaneCheck') } -// architectureTest runs on the `test` runtime (runtimeFrom above) plus its own configuration, so -// the capability leaves declared `architectureTestRuntimeOnly` reach the whole-repository ArchUnit -// import without reaching the default composition that `test` and `systemTest` boot. -sourceSets.architectureTest.runtimeClasspath += configurations.architectureTestRuntimeClasspath +// architectureTest runs on the `test` runtime plus its own configuration, so the capability leaves +// declared `architectureTestRuntimeOnly` reach the whole-repository ArchUnit import without reaching +// the default composition that `test` and `systemTest` boot. Its compile classpath (test fixtures, +// testCompileOnly analysis dependencies) is deliberately not its runtime. +sourceSets.architectureTest.runtimeClasspath = sourceSets.architectureTest.output + + sourceSets.test.runtimeClasspath + configurations.architectureTestRuntimeClasspath // The full-boot lane boots the composition bootJar packages. It compiles against everything the // test lane sees, but it runs on the main runtime graph plus the test frameworks — not on the test @@ -95,10 +115,6 @@ dependencies { systemTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' } -// architectureTest compiles against test fixtures but intentionally mirrors the ordinary test -// runtime rather than its compile classpath. `runtimeFrom 'test'` above keeps testCompileOnly -// analysis dependencies out of that lane. - sourceSets { conditionalTransportBuildContractTest { java.srcDir 'src/conditionalTransportBuildContractTest/java' diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 795e58db..0aa777dd 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -691,7 +691,12 @@ class ApplicationBoundaryArchitectureTest { // The template's IntegrationEventEncoderPort: a deterministic in-memory rendering of the // application's own envelope, no IO — the same shape as the identifier codecs. Only this // package; the rest of support stays covered. - || packageName.contains(".adapter.outbound.support.messaging"); + || packageName.contains(".adapter.outbound.support.messaging") + // The Fileserver's access policies: a role-and-owner decision over values already in hand, + // no IO. Every Fileserver use case asks it before acting, so without this every one of them + // would have to claim an external outbound call it never makes. Only this package; the + // storage, verification and audit adapters beside it stay covered. + || packageName.contains(".adapter.outbound.fileserver.platform.security"); } @ArchTest diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java index a1e0e9c0..a525fd3f 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java @@ -38,8 +38,8 @@ import org.springframework.stereotype.Component; * selects that implementation but does not implement the port. * *

The rule has no exceptions any more. Its one allowlisted class, the metering decorator {@code - * MeteredDistributedLockPort}, moved to {@code adapter:outbound:persistence-jpa} with the JDBC lock - * it decorates. + * MeteredDistributedLock}, moved to {@code adapter:outbound:persistence-jpa} with the JDBC lock it + * decorates. */ @AnalyzeClasses( packages = "dev.caskeleton.bootstrap", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/FileserverUseCaseContractDeviationTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/FileserverUseCaseContractDeviationTest.java index ead1a19f..a7ddeee5 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/FileserverUseCaseContractDeviationTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/FileserverUseCaseContractDeviationTest.java @@ -12,23 +12,24 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** - * Freezes the Fileserver's exemption from the inbound use-case contract. + * Freezes what is left of the Fileserver's exemption from the inbound use-case contract. * *

{@code application-core/CLAUDE.md} requires every inbound port implementation to extend {@code * CommandUseCase} or {@code QueryUseCase} and to declare {@code @UseCaseCapability}. The ArchUnit - * rules that enforce it — {@code INBOUND_PORT_IMPLEMENTATIONS_END_WITH_USE_CASE} and {@code - * INBOUND_PORT_IMPLEMENTATIONS_DECLARE_CAPABILITY} — only match types that implement {@link - * UseCase}. A service that never does is not caught; it is invisible to them. + * rules that enforce it only match types that implement {@link UseCase}; a service that never does + * is invisible to them. * - *

That is why the Fileserver's multi-method services pass the build today while declaring none - * of the transaction mode, idempotency or repository access every other checked use case declares. - * Resolving it properly means roughly thirty command/query use cases and a decision about where the - * shared status vocabulary lives — an ADR, recorded as open in {@code - * docs/fileserver/design-deviations.md} §5. + *

Every operation the transport reaches is now a use case (owner decision 32): one port per + * operation under {@code application.fileserver.port.in}, each implementation declaring its + * capability and, for the writes, a {@code file:*} permission. What remains here is what no + * transport calls. The cleanup and reconciliation services are driven by background workers that + * have no caller identity; a mutating use case must declare a permission + * (MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION), and a permission a scheduler cannot hold would + * refuse every run. The writer-lease coordinator is a collaborator the append use case holds, not + * an entrypoint. * - *

Until then the exemption is frozen rather than open-ended. A new Fileserver application - * service fails this test, so the deviation cannot quietly grow while the decision is pending, and - * removing an entry as it is converted is a one-line change that records the progress. + *

A new Fileserver application service still fails this test, so the exemption cannot quietly + * grow back. */ class FileserverUseCaseContractDeviationTest { @@ -39,16 +40,7 @@ class FileserverUseCaseContractDeviationTest { * a pattern would silently absorb the next service, which is the behaviour being prevented. */ private static final Set KNOWN_DEVIATIONS = - Set.of( - "DefaultUploadApplicationService", - "DefaultDownloadApplicationService", - "DefaultFinalizeUploadService", - "DefaultSingleShotUploadService", - "DefaultFileLifecycleService", - "DefaultFileserverAdminService", - "DefaultCleanupService", - "DefaultFileReconciliationService", - "WriterLeaseCoordinator"); + Set.of("DefaultCleanupService", "DefaultFileReconciliationService", "WriterLeaseCoordinator"); @Test @DisplayName("no new Fileserver application service may bypass the use-case contract") @@ -76,9 +68,8 @@ class FileserverUseCaseContractDeviationTest { .as( "a Fileserver application service that is not a use case declares none of the " + "transaction mode, idempotency or repository access the contract requires, and " - + "the ArchUnit rules cannot see it. Convert it, or — if the ADR in " - + "docs/fileserver/design-deviations.md §5 is still open — add it here and say why " - + "in the pull request.") + + "the ArchUnit rules cannot see it. Make it a use case behind a port.in " + + "interface (docs/fileserver/design-deviations.md §5).") .allSatisfy(name -> assertThat(KNOWN_DEVIATIONS).contains(name)); } diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java index 74d7283b..171d1e87 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java @@ -14,7 +14,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; *

The naming/idiom SSOT is {@code code-conventions.md}. This test enforces only the rules that * ArchUnit can decide reliably (N6, I5). {@code [판단]} naming rules (N2/N7/N8/...) and rules with * intentional project exceptions (N3/N4 — e.g. the {@code IdFactory} domain port, the {@code - * SpringTransactionPort} canonical impl) stay in {@code ca-quality-reviewer} (doc+review), per the + * SpringTransaction} canonical impl) stay in {@code ca-quality-reviewer} (doc+review), per the * code-conventions enforcement matrix. */ @AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class) diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java index de45ff70..0944f6e0 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java @@ -4,8 +4,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; +import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter; +import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; +import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy; +import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry; +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; -import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; @@ -28,13 +34,17 @@ import java.time.Clock; import java.util.Comparator; import java.util.HexFormat; import java.util.List; +import java.util.Set; import java.util.stream.Stream; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.context.annotation.Bean; @@ -43,7 +53,8 @@ import org.springframework.context.annotation.Import; import org.springframework.core.task.TaskDecorator; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.web.servlet.MockMvc; @@ -103,6 +114,9 @@ import tools.jackson.databind.ObjectMapper; "app.object-storage.enabled=false", "app.fileserver-platform.instance-id=round-trip-node", "app.fileserver-platform.security.access-policy=role-based", + // A second write tier that no permission mapping names: the fileserver's own policy admits + // it, so a refusal can only come from the permission gate in front of the use case. + "app.fileserver-platform.security.write-roles=ROLE_FILE_WRITE,ROLE_UNMAPPED_WRITER", // Metrics are a separate concern with their own tests; leaving them off keeps a MeterRegistry // out of a context that would otherwise need one only to satisfy a bean signature. "app.fileserver-platform.observability.metrics-enabled=false", @@ -111,10 +125,14 @@ import tools.jackson.databind.ObjectMapper; // real filesystem, so a developer machine with a 90%-full disk would otherwise fail this // test for a reason that has nothing to do with the seams under test. "app.fileserver-platform.quota.soft-high-water=0.99", - "app.fileserver-platform.quota.hard-high-water=1.0" + "app.fileserver-platform.quota.hard-high-water=1.0", + // The fileserver's tiers grant their permissions, as security.yml ships them. This + // environment loads no configuration file, so the mapping is restated rather than read. + "ca-skeleton.authz.role-permissions[ROLE_FILE_READ]=file:read", + "ca-skeleton.authz.role-permissions[ROLE_FILE_WRITE]=file:upload,file:delete,file:copy," + + "file:move" }) @AutoConfigureMockMvc(addFilters = false) -@WithMockUser(authorities = {"ROLE_FILE_READ", "ROLE_FILE_WRITE"}) class FileserverCompositionIntegrationTest { private static final String CORE_CAPABILITY = "jpa-flyway-migration"; @@ -137,6 +155,24 @@ class FileserverCompositionIntegrationTest { @Autowired private ObjectMapper objectMapper; + /** + * The caller every test acts as unless it says otherwise: a reader and writer. + * + *

An {@link AuthenticatedPrincipal}, not a mock user. Method security resolves permissions + * from the principal's roles, and any other principal type is refused outright — which is exactly + * what a {@code @WithMockUser} caller would have been once the upload became a permissioned use + * case. With the filter chain off, nothing else would put a caller in the security context. + */ + @BeforeEach + void actAsReaderAndWriter() { + actAs(Set.of("ROLE_FILE_READ", "ROLE_FILE_WRITE")); + } + + @AfterEach + void forgetTheCaller() { + SecurityContextHolder.clearContext(); + } + /** * Applies the operator-owned schema streams and points the runtime at the container. * @@ -229,18 +265,58 @@ class FileserverCompositionIntegrationTest { * actually reaches it: the same request that succeeds above fails here on the roles alone. */ @Test - @WithMockUser(authorities = "ROLE_UNRELATED") void downloadWithoutTheReadRoleIsRefused() throws Exception { - MvcResult refused = - mockMvc.perform(get("/v1/files/{fileId}/content", knownFileId())).andReturn(); + String fileId = knownFileId(); + actAs(Set.of("ROLE_UNRELATED")); + + MvcResult refused = mockMvc.perform(get("/v1/files/{fileId}/content", fileId)).andReturn(); assertThat(refused.getResponse().getStatus()).isEqualTo(403); } + /** + * The fileserver's tier is not the whole of a write's authority. + * + *

{@code ROLE_UNMAPPED_WRITER} is a write tier the fileserver's policy admits, but no role + * mapping grants it {@code file:upload}. The upload is refused by the permission gate on the use + * case's proxy — the one this composition gets from the web adapter's method security — before + * the fileserver's own policy or any storage is reached, so nothing is staged. + */ + @Test + void anUploadByATierWithoutTheUploadPermissionIsRefusedBeforeAnythingIsStaged() throws Exception { + // given + actAs(Set.of("ROLE_FILE_READ", "ROLE_UNMAPPED_WRITER")); + + // when + MvcResult refused = + mockMvc + .perform( + post("/v1/files:raw") + .header(RawUploadRequestMapper.FILENAME_HEADER, "refused.txt") + .contentType(MediaType.TEXT_PLAIN) + .content(CONTENT)) + .andReturn(); + + // then + assertThat(List.of(refused.getResponse().getStatus(), stagingObjects())) + .containsExactly(403, List.of()); + } + // ========================================================================= // helpers // ========================================================================= + // With the filter chain off nothing copies a test authentication into the security context, so + // the caller is placed there directly; MockMvc dispatches on this thread. + private static void actAs(Set roles) { + SecurityContextHolder.getContext() + .setAuthentication( + new TestingAuthenticationToken( + new AuthenticatedPrincipal("uploader", "uploader@example.test", roles), + "n/a", + List.of())); + } + /** Uploads one file over the raw streaming endpoint and returns the parsed answer. */ private JsonNode upload(byte[] content, String filename) throws Exception { MvcResult result = @@ -425,7 +501,17 @@ class FileserverCompositionIntegrationTest { // declarations over overlapping packages produced a duplicate uploadLeaseRepository definition — // and, more to the point, a test that declared its own scan would keep passing if the shipped one // were ever registered nowhere, which is exactly the failure this arrangement exists to catch. - @Import({FileserverPlatformAutoConfiguration.class, DomainContextConfig.class}) + @EnableConfigurationProperties(RolePermissionPolicy.class) + @Import({ + FileserverPlatformAutoConfiguration.class, + DomainContextConfig.class, + // The permission gate the running application puts in front of every fileserver write, and + // the handler that answers its refusal. Without them a @RequiresPermission is only a marker. + MethodSecurityConfig.class, + AuthorizationAdapter.class, + RolePermissionRegistry.class, + GlobalExceptionHandler.class + }) static class FileserverRuntime { @Bean @@ -436,14 +522,14 @@ class FileserverCompositionIntegrationTest { /** * The production transaction port, named rather than scanned. * - *

{@code SpringTransactionPort} is a {@code @Component} the running application picks up - * from {@code dev.caskeleton.adapter.outbound.persistence}. Constructing it here keeps the scan + *

{@code SpringTransaction} is a {@code @Component} the running application picks up from + * {@code dev.caskeleton.adapter.outbound.persistence}. Constructing it here keeps the scan * narrow without substituting a different implementation — the boundaries under test are the * real ones, over the real transaction manager. */ @Bean TransactionPort transactions(PlatformTransactionManager transactionManager) { - return new SpringTransactionPort(transactionManager); + return new SpringTransaction(transactionManager); } /** diff --git a/src/app-bootstrap/src/main/resources/config/security.yml b/src/app-bootstrap/src/main/resources/config/security.yml index a2a4d21a..f9cb2b7b 100644 --- a/src/app-bootstrap/src/main/resources/config/security.yml +++ b/src/app-bootstrap/src/main/resources/config/security.yml @@ -47,6 +47,16 @@ ca-skeleton: # a caller that may start an operation may cancel its own, and reading one needs no # permission beyond being the one who submitted it. operation-submit: operation:submit,operation:cancel + # Fileserver (/v1/files, /v1/uploads, /internal/fileserver; on with the fileserver module). + # Keyed by the fileserver's own default tier roles (app.fileserver-platform.security.*-roles), + # so one role grants both halves of a fileserver write: the permission here, checked on the + # use case, and the tier FileAccessPolicyPort checks inside it along with ownership. The + # brackets keep the underscores, which unbracketed map keys lose in binding. A deployment that + # renames those roles maps its own names here too. The tiers do not inherit, and neither do + # these: a writer that also reads holds both roles. + "[ROLE_FILE_READ]": file:read + "[ROLE_FILE_WRITE]": file:upload,file:delete,file:copy,file:move + "[ROLE_FILE_ADMIN]": file:admin cors: # true | false enabled: ${APP_SECURITY_CORS_ENABLED:false} diff --git a/src/application-core/README.md b/src/application-core/README.md index 97864c52..e1b11796 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -103,7 +103,7 @@ deterministic writer, Kafka ACK producer, PostgreSQL outbox append/relay는 후 - **존재 이유**: application 유스케이스가 `org.springframework.transaction.annotation.Transactional` 을 import 하지 않고도 트랜잭션 의도를 선언하게 하기 위한 추상화다. 구현(보통 - `SpringTransactionPort`)은 persistence adapter 가 Spring `PlatformTransactionManager` 로 제공한다. + `SpringTransaction`)은 persistence adapter 가 Spring `PlatformTransactionManager` 로 제공한다. application/domain 을 프레임워크-free 로 유지하는 핵심 장치. - 네 가지 경계: - `inWrite` — REQUIRED + read-write, `READ_COMMITTED`. command 유스케이스 기본. @@ -244,7 +244,7 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 - 상태: `CLAIMED` / `EXECUTING` / `COMPLETED` / `FAILED_RETRYABLE` / `ABANDONED`(`IdempotencyState`). - 구현은 provider 하나만 붙는다: `redis`(`adapter:outbound:cache-redis` `RedisIdempotencyStoreAdapter`) 또는 `postgresql`(`adapter:outbound:persistence-jpa` - `PostgreSqlOwnerSafeIdempotencyStore`). `ca-skeleton.capabilities.idempotency.provider` 로 고르고 + `PostgreSqlIdempotencyStore`). `ca-skeleton.capabilities.idempotency.provider` 로 고르고 기본값은 `disabled` 다. store 가 정확히 하나가 아니면 기동을 거부한다. - **in-memory 프로덕션 구현 금지**. 테스트용 `InMemoryIdempotencyStore` 는 testFixtures 에만 있다. diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPort.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPort.java index f710eefb..33bff3f5 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPort.java @@ -5,7 +5,7 @@ import java.util.function.Supplier; /** * Outbound port for application-managed transaction boundaries: use cases declare transactional * intent without importing Spring's {@code @Transactional}. The persistence adapter (typically - * {@code SpringTransactionPort}) implements it over Spring's {@code PlatformTransactionManager}. + * {@code SpringTransaction}) implements it over Spring's {@code PlatformTransactionManager}. * *

    *
  • {@link #inWrite(Supplier)} — REQUIRED + read-write, {@code READ_COMMITTED}. Command diff --git a/src/application-core/src/test/java/dev/caskeleton/application/transaction/IsolationTest.java b/src/application-core/src/test/java/dev/caskeleton/application/transaction/IsolationTest.java index 2696cf6c..4051f3e4 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/transaction/IsolationTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/transaction/IsolationTest.java @@ -11,8 +11,8 @@ import org.junit.jupiter.api.Test; * feature-transaction-concurrency-contract D3 / §구현 가이드 1 — isolation vocabulary policy. * *

    This branch owns the {@link Isolation} vocabulary. {@code READ_COMMITTED} is the pinned - * default (every {@code SpringTransactionPort} template pins it explicitly — see {@code - * SpringTransactionPortTest}); {@code REPEATABLE_READ}/{@code SERIALIZABLE} are the explicit opt-in + * default (every {@code SpringTransaction} template pins it explicitly — see {@code + * SpringTransactionTest}); {@code REPEATABLE_READ}/{@code SERIALIZABLE} are the explicit opt-in * levels for write-heavy / read-consistency use cases; {@code READ_UNCOMMITTED} is forbidden and * therefore MUST NOT be a DECLARED constant. * diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/AdminAudit.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/AdminAudit.java new file mode 100644 index 00000000..f548317a --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/AdminAudit.java @@ -0,0 +1,74 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint; +import java.time.Clock; +import java.util.Objects; + +/** + * The audit trail and page cap every operator action shares. + * + *

    Public because the use cases that write it are assembled outside this package; nothing but the + * admin use cases constructs one. + */ +public final class AdminAudit { + + private static final int MAXIMUM_ADMIN_PAGE = 1000; + + private final AdminAuditPort auditPort; + private final SafeFileFingerprint fingerprint; + private final Clock clock; + + public AdminAudit(AdminAuditPort auditPort, SafeFileFingerprint fingerprint, Clock clock) { + this.auditPort = Objects.requireNonNull(auditPort, "auditPort"); + this.fingerprint = Objects.requireNonNull(fingerprint, "fingerprint"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Caps every admin query. + * + *

    An unbounded admin listing is a self-inflicted outage: it walks production storage or the + * whole metadata table on an operator's keystroke. + */ + static int boundedLimit(int requested) { + return Math.max(1, Math.min(requested, MAXIMUM_ADMIN_PAGE)); + } + + void record( + String operation, + String reasonCode, + RequestContext context, + boolean succeeded, + String subjectId) { + auditPort.record( + new AdminAuditRecord( + operation, + reasonCode, + actorFingerprint(context), + context.traceId(), + succeeded, + subjectFingerprint(subjectId), + clock.instant())); + } + + /** + * Stable pseudonym for the acting operator. + * + *

    An audit trail needs to correlate actions by the same actor without becoming a second + * directory of who works here, so the principal is reduced to a fingerprint. + * + *

    A keyed HMAC, not {@code hashCode()}. A 32-bit unkeyed hash over an enumerable identifier + * space is reversible with a laptop and collides often enough that two operators can share a + * pseudonym — which is worse than no pseudonym, because the trail then reads as if one person did + * both things. + */ + private String actorFingerprint(RequestContext context) { + return fingerprint.of(context.subject().principalId()); + } + + /** The same reduction for the object of the action; a raw file id is a disclosure too. */ + private String subjectFingerprint(String subjectId) { + return subjectId.isBlank() ? subjectId : fingerprint.of(subjectId); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/CleanupUploadsApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/CleanupUploadsApplicationUseCase.java new file mode 100644 index 00000000..c996ad66 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/CleanupUploadsApplicationUseCase.java @@ -0,0 +1,54 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult; +import dev.caskeleton.application.fileserver.cleanup.CleanupService; +import dev.caskeleton.application.fileserver.port.in.CleanupUploadsCommand; +import dev.caskeleton.application.fileserver.port.in.CleanupUploadsUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.util.Objects; +import java.util.Optional; + +/** + * Runs one cleanup batch on an operator's request. + * + *

    {@code RepositoryAccess.NONE}: the batch is {@link CleanupService}'s, which opens a boundary + * per claimed item. One around the whole batch would hold a connection across every deletion. + */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE, + crossTenantAdmin = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class CleanupUploadsApplicationUseCase implements CleanupUploadsUseCase { + + private final CleanupService cleanupService; + private final FileAccessPolicyPort accessPolicy; + private final AdminAudit audit; + + public CleanupUploadsApplicationUseCase( + CleanupService cleanupService, FileAccessPolicyPort accessPolicy, AdminAudit audit) { + this.cleanupService = Objects.requireNonNull(cleanupService, "cleanupService"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.audit = Objects.requireNonNull(audit, "audit"); + } + + @Override + public CleanupBatchResult handle(CleanupUploadsCommand command) { + RequestContext context = command.context(); + accessPolicy.authorize(FileOperation.ADMIN_FORCE_DELETE, context.subject(), Optional.empty()); + CleanupBatchResult result = + cleanupService.runBatch(AdminAudit.boundedLimit(command.maxItems()), command.maxBytes()); + audit.record("uploads:cleanup", "OPERATOR_CLEANUP", context, true, "batch"); + return result; + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/DefaultFileserverAdminService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/DefaultFileserverAdminService.java deleted file mode 100644 index 5a932fdd..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/DefaultFileserverAdminService.java +++ /dev/null @@ -1,272 +0,0 @@ -package dev.caskeleton.application.fileserver.admin; - -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.FileState; -import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; -import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; -import dev.caskeleton.application.fileserver.api.error.FileserverException; -import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; -import dev.caskeleton.application.fileserver.api.metadata.FileRecord; -import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; -import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; -import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; -import dev.caskeleton.application.fileserver.api.security.FileOperation; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult; -import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; -import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; -import dev.caskeleton.application.fileserver.cleanup.CleanupService; -import dev.caskeleton.application.fileserver.cleanup.FileRetirement; -import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint; -import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; -import dev.caskeleton.application.fileserver.upload.FileView; -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * The management plane, with its own authority and its own audit trail. - * - *

    Two rules shape everything here. A reconcile is a dry run unless the caller explicitly opted - * out and echoed the fingerprints it was shown, so a stale scan can never turn into a mass - * delete. And every mutating action is audited whether it succeeded or not, because a refused - * force-delete is exactly the event a reviewer needs to see. - */ -public final class DefaultFileserverAdminService implements FileserverAdminService { - - private static final int MAXIMUM_ADMIN_PAGE = 1000; - - private final StorageHealthPort healthPort; - private final OrphanScanPort orphanScanPort; - private final FileMetadataPort metadataStore; - private final UploadSessionPort sessionStore; - private final StagingUploadLocatorPort stagingLocator; - private final CleanupQueuePort cleanupQueue; - private final FileRetirement retirement; - private final CleanupService cleanupService; - private final FileAccessPolicyPort accessPolicy; - private final AdminAuditPort auditPort; - private final SafeFileFingerprint fingerprint; - private final TransactionPort transactions; - private final Clock clock; - - public DefaultFileserverAdminService( - StorageHealthPort healthPort, - OrphanScanPort orphanScanPort, - FileMetadataPort metadataStore, - UploadSessionPort sessionStore, - StagingUploadLocatorPort stagingLocator, - CleanupQueuePort cleanupQueue, - CleanupService cleanupService, - FileAccessPolicyPort accessPolicy, - AdminAuditPort auditPort, - SafeFileFingerprint fingerprint, - TransactionPort transactions, - Clock clock) { - this.healthPort = healthPort; - this.orphanScanPort = orphanScanPort; - this.metadataStore = metadataStore; - this.sessionStore = sessionStore; - this.stagingLocator = stagingLocator; - this.cleanupQueue = cleanupQueue; - this.cleanupService = cleanupService; - this.accessPolicy = accessPolicy; - this.auditPort = auditPort; - this.fingerprint = fingerprint; - this.transactions = transactions; - this.clock = clock; - this.retirement = new FileRetirement(metadataStore, cleanupQueue); - } - - @Override - public StorageHealthReport storageHealth(RequestContext context) { - authorizeRead(context); - return healthPort.health(); - } - - @Override - public RuntimeCapabilityReport capabilities(RequestContext context) { - authorizeRead(context); - return healthPort.capabilities(); - } - - @Override - public List orphans(int limit, RequestContext context) { - authorizeRead(context); - return orphanScanPort.scan(boundedLimit(limit)); - } - - @Override - public OrphanReconcileReport reconcileOrphans( - OrphanReconcileCommand command, RequestContext context) { - accessPolicy.authorize(FileOperation.ADMIN_FORCE_DELETE, context.subject(), Optional.empty()); - List candidates = orphanScanPort.scan(boundedLimit(command.limit())); - if (command.dryRun()) { - audit("orphans:reconcile", command.reasonCode(), context, true, "dry-run"); - return new OrphanReconcileReport(true, candidates, 0, 0, 0); - } - - int deleted = 0; - int mismatched = 0; - long reclaimed = 0; - for (OrphanObject candidate : candidates) { - if (!command.expectedFingerprints().contains(candidate.fingerprint())) { - mismatched++; - continue; - } - if (reclaimed + candidate.sizeBytes() > command.maxBytes()) { - break; - } - if (orphanScanPort.deleteIfFingerprintMatches( - candidate.contentKey(), candidate.fingerprint())) { - // Retirement moved the object to quarantine; the durable record of that intent is queued - // immediately after. Without it a node that dies here leaves an object nobody is looking - // for, in an area nothing scans. - transactions.inWrite( - () -> cleanupQueue.enqueue(CleanupRequest.forOrphan(candidate.contentKey()))); - deleted++; - reclaimed += candidate.sizeBytes(); - } else { - mismatched++; - } - } - audit("orphans:reconcile", command.reasonCode(), context, true, "apply"); - return new OrphanReconcileReport(false, candidates, deleted, mismatched, reclaimed); - } - - @Override - public FileView reverify(FileId fileId, RequestContext context) { - accessPolicy.authorize(FileOperation.ADMIN_REVERIFY, context.subject(), Optional.empty()); - FileRecord record = requireRecord(fileId); - if (record.state() != FileState.QUARANTINED) { - audit("files:reverify", "REVERIFY_REJECTED", context, false, fileId.canonicalText()); - throw new FileserverException( - "only a quarantined file can be re-verified", - FileserverFailureContext.forFileState( - FileserverErrorCode.FILE_NOT_READY, fileId, record.state(), false)); - } - FileRecord verifying = - transactions.inWrite( - () -> - metadataStore.transition( - record.fileId(), - record.version(), - FileState.QUARANTINED, - FileState.VERIFYING, - FileRecordMutation.none())); - audit("files:reverify", "OPERATOR_REVERIFY", context, true, fileId.canonicalText()); - return FileView.of(verifying.toDescriptor()); - } - - @Override - public void forceDelete(ForceDeleteCommand command, RequestContext context) { - accessPolicy.authorize(FileOperation.ADMIN_FORCE_DELETE, context.subject(), Optional.empty()); - FileRecord record = requireRecord(command.fileId()); - // An operator force-delete must not be able to leave a file unreachable with nothing queued to - // reclaim its bytes, so retiring the record and queueing the content commit together — and an - // upload still in progress ends with it, exactly as a data-plane delete does. - transactions.inWrite( - () -> retirement.retireWithUnfinishedUpload(record, sessionStore, stagingLocator)); - audit( - "files:force-delete", - command.reasonCode(), - context, - true, - command.fileId().canonicalText()); - } - - @Override - public List incompleteUploads(int limit, RequestContext context) { - authorizeRead(context); - List views = new ArrayList<>(); - for (UploadSession session : sessionStore.findExpired(clock.instant(), boundedLimit(limit))) { - views.add( - new IncompleteUploadView( - session.uploadId(), - session.fileId(), - session.committedOffset(), - session.expiresAt(), - session.leaseOwner(), - session.leaseUntil())); - } - return List.copyOf(views); - } - - @Override - public CleanupBatchResult cleanupUploads(int maxItems, long maxBytes, RequestContext context) { - accessPolicy.authorize(FileOperation.ADMIN_FORCE_DELETE, context.subject(), Optional.empty()); - CleanupBatchResult result = cleanupService.runBatch(boundedLimit(maxItems), maxBytes); - audit("uploads:cleanup", "OPERATOR_CLEANUP", context, true, "batch"); - return result; - } - - /** - * Management-plane reads are an admin operation, not a metadata read: a data-plane reader must - * not learn storage health or list other callers' incomplete uploads. - */ - private void authorizeRead(RequestContext context) { - accessPolicy.authorize(FileOperation.ADMIN_READ, context.subject(), Optional.empty()); - } - - /** - * Caps every admin query. - * - *

    An unbounded admin listing is a self-inflicted outage: it walks production storage or the - * whole metadata table on an operator's keystroke. - */ - private static int boundedLimit(int requested) { - return Math.max(1, Math.min(requested, MAXIMUM_ADMIN_PAGE)); - } - - private void audit( - String operation, - String reasonCode, - RequestContext context, - boolean succeeded, - String subjectId) { - auditPort.record( - new AdminAuditRecord( - operation, - reasonCode, - actorFingerprint(context), - context.traceId(), - succeeded, - subjectFingerprint(subjectId), - clock.instant())); - } - - /** - * Stable pseudonym for the acting operator. - * - *

    An audit trail needs to correlate actions by the same actor without becoming a second - * directory of who works here, so the principal is reduced to a fingerprint. - * - *

    A keyed HMAC, not {@code hashCode()}. A 32-bit unkeyed hash over an enumerable identifier - * space is reversible with a laptop and collides often enough that two operators can share a - * pseudonym — which is worse than no pseudonym, because the trail then reads as if one person did - * both things. - */ - private String actorFingerprint(RequestContext context) { - return fingerprint.of(context.subject().principalId()); - } - - /** The same reduction for the object of the action; a raw file id is a disclosure too. */ - private String subjectFingerprint(String subjectId) { - return subjectId.isBlank() ? subjectId : fingerprint.of(subjectId); - } - - private FileRecord requireRecord(FileId fileId) { - return metadataStore - .find(fileId) - .orElseThrow( - () -> - new FileNotFoundException( - "file record does not exist", - FileserverFailureContext.forFile( - FileserverErrorCode.FILE_NOT_FOUND, fileId, false))); - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/FileserverAdminService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/FileserverAdminService.java deleted file mode 100644 index dfab48bc..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/FileserverAdminService.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.application.fileserver.admin; - -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.upload.FileView; -import java.util.List; - -/** - * The management-plane surface. - * - *

    Every method here is deliberately separate from the public application services: an operator - * action is authorized against a different authority, is always audited, and may see counters a - * tenant never should. Mixing them into the public services is how an admin capability ends up one - * missing check away from being publicly reachable. - */ -public interface FileserverAdminService { - - StorageHealthReport storageHealth(RequestContext context); - - RuntimeCapabilityReport capabilities(RequestContext context); - - List orphans(int limit, RequestContext context); - - OrphanReconcileReport reconcileOrphans(OrphanReconcileCommand command, RequestContext context); - - FileView reverify(FileId fileId, RequestContext context); - - void forceDelete(ForceDeleteCommand command, RequestContext context); - - List incompleteUploads(int limit, RequestContext context); - - CleanupBatchResult cleanupUploads(int maxItems, long maxBytes, RequestContext context); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteFileApplicationUseCase.java new file mode 100644 index 00000000..730d4098 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteFileApplicationUseCase.java @@ -0,0 +1,81 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.FileRetirement; +import dev.caskeleton.application.fileserver.port.in.ForceDeleteCommand; +import dev.caskeleton.application.fileserver.port.in.ForceDeleteFileUseCase; +import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** + * Removes a file on an operator's authority, bypassing the data-plane preconditions. + * + *

    An operator force-delete must not be able to leave a file unreachable with nothing queued to + * reclaim its bytes, so retiring the record and queueing the content commit together — and an + * upload still in progress ends with it, exactly as a data-plane delete does. + */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + crossTenantAdmin = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class ForceDeleteFileApplicationUseCase implements ForceDeleteFileUseCase { + + private final FileMetadataPort metadataStore; + private final UploadSessionPort sessionStore; + private final StagingUploadLocatorPort stagingLocator; + private final FileRetirement retirement; + private final FileAccessPolicyPort accessPolicy; + private final AdminAudit audit; + private final TransactionPort transactions; + + public ForceDeleteFileApplicationUseCase( + FileMetadataPort metadataStore, + UploadSessionPort sessionStore, + StagingUploadLocatorPort stagingLocator, + CleanupQueuePort cleanupQueue, + FileAccessPolicyPort accessPolicy, + AdminAudit audit, + TransactionPort transactions) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.sessionStore = Objects.requireNonNull(sessionStore, "sessionStore"); + this.stagingLocator = Objects.requireNonNull(stagingLocator, "stagingLocator"); + this.retirement = new FileRetirement(metadataStore, cleanupQueue); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.audit = Objects.requireNonNull(audit, "audit"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public Void handle(ForceDeleteCommand command) { + RequestContext context = command.context(); + accessPolicy.authorize(FileOperation.ADMIN_FORCE_DELETE, context.subject(), Optional.empty()); + FileRecord record = FileRecords.require(metadataStore, command.fileId()); + transactions.inWrite( + () -> retirement.retireWithUnfinishedUpload(record, sessionStore, stagingLocator)); + audit.record( + "files:force-delete", + command.reasonCode(), + context, + true, + command.fileId().canonicalText()); + return null; + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetRuntimeCapabilitiesApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetRuntimeCapabilitiesApplicationUseCase.java new file mode 100644 index 00000000..5143bb37 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetRuntimeCapabilitiesApplicationUseCase.java @@ -0,0 +1,40 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.GetRuntimeCapabilitiesQuery; +import dev.caskeleton.application.fileserver.port.in.GetRuntimeCapabilitiesUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.util.Objects; +import java.util.Optional; + +/** Reports what the running storage supports to an operator. */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class GetRuntimeCapabilitiesApplicationUseCase implements GetRuntimeCapabilitiesUseCase { + + private final StorageHealthPort healthPort; + private final FileAccessPolicyPort accessPolicy; + + public GetRuntimeCapabilitiesApplicationUseCase( + StorageHealthPort healthPort, FileAccessPolicyPort accessPolicy) { + this.healthPort = Objects.requireNonNull(healthPort, "healthPort"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + } + + @Override + public RuntimeCapabilityReport handle(GetRuntimeCapabilitiesQuery query) { + accessPolicy.authorize(FileOperation.ADMIN_READ, query.context().subject(), Optional.empty()); + return healthPort.capabilities(); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetStorageHealthApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetStorageHealthApplicationUseCase.java new file mode 100644 index 00000000..2e1a0de1 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/GetStorageHealthApplicationUseCase.java @@ -0,0 +1,45 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.GetStorageHealthQuery; +import dev.caskeleton.application.fileserver.port.in.GetStorageHealthUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.util.Objects; +import java.util.Optional; + +/** + * Reports the storage's health to an operator. + * + *

    A management-plane read is an admin operation, not a metadata read: a data-plane reader must + * not learn storage health. + */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class GetStorageHealthApplicationUseCase implements GetStorageHealthUseCase { + + private final StorageHealthPort healthPort; + private final FileAccessPolicyPort accessPolicy; + + public GetStorageHealthApplicationUseCase( + StorageHealthPort healthPort, FileAccessPolicyPort accessPolicy) { + this.healthPort = Objects.requireNonNull(healthPort, "healthPort"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + } + + @Override + public StorageHealthReport handle(GetStorageHealthQuery query) { + accessPolicy.authorize(FileOperation.ADMIN_READ, query.context().subject(), Optional.empty()); + return healthPort.health(); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListIncompleteUploadsApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListIncompleteUploadsApplicationUseCase.java new file mode 100644 index 00000000..b353b655 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListIncompleteUploadsApplicationUseCase.java @@ -0,0 +1,72 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.ListIncompleteUploadsQuery; +import dev.caskeleton.application.fileserver.port.in.ListIncompleteUploadsUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * Lists uploads that expired before they finished. + * + *

    An admin read: a data-plane reader must not list other callers' incomplete uploads. + */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.READ_REPOSITORY, + crossTenantAdmin = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class ListIncompleteUploadsApplicationUseCase implements ListIncompleteUploadsUseCase { + + private final UploadSessionPort sessionStore; + private final FileAccessPolicyPort accessPolicy; + private final TransactionPort transactions; + private final Clock clock; + + public ListIncompleteUploadsApplicationUseCase( + UploadSessionPort sessionStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions, + Clock clock) { + this.sessionStore = Objects.requireNonNull(sessionStore, "sessionStore"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public List handle(ListIncompleteUploadsQuery query) { + accessPolicy.authorize(FileOperation.ADMIN_READ, query.context().subject(), Optional.empty()); + List expired = + transactions.inRead( + () -> + sessionStore.findExpired(clock.instant(), AdminAudit.boundedLimit(query.limit()))); + List views = new ArrayList<>(); + for (UploadSession session : expired) { + views.add( + new IncompleteUploadView( + session.uploadId(), + session.fileId(), + session.committedOffset(), + session.expiresAt(), + session.leaseOwner(), + session.leaseUntil())); + } + return List.copyOf(views); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListOrphansApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListOrphansApplicationUseCase.java new file mode 100644 index 00000000..86412cee --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ListOrphansApplicationUseCase.java @@ -0,0 +1,41 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.ListOrphansQuery; +import dev.caskeleton.application.fileserver.port.in.ListOrphansUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** Lists physical objects no record refers to. */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class ListOrphansApplicationUseCase implements ListOrphansUseCase { + + private final OrphanScanPort orphanScanPort; + private final FileAccessPolicyPort accessPolicy; + + public ListOrphansApplicationUseCase( + OrphanScanPort orphanScanPort, FileAccessPolicyPort accessPolicy) { + this.orphanScanPort = Objects.requireNonNull(orphanScanPort, "orphanScanPort"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + } + + @Override + public List handle(ListOrphansQuery query) { + accessPolicy.authorize(FileOperation.ADMIN_READ, query.context().subject(), Optional.empty()); + return orphanScanPort.scan(AdminAudit.boundedLimit(query.limit())); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReconcileOrphansApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReconcileOrphansApplicationUseCase.java new file mode 100644 index 00000000..aac6eeaf --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReconcileOrphansApplicationUseCase.java @@ -0,0 +1,88 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; +import dev.caskeleton.application.fileserver.port.in.OrphanReconcileCommand; +import dev.caskeleton.application.fileserver.port.in.ReconcileOrphansUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** Removes, or with a dry run only lists, the orphaned objects an operator names. */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + externalOutboundAllowed = true, + crossTenantAdmin = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class ReconcileOrphansApplicationUseCase implements ReconcileOrphansUseCase { + + private final OrphanScanPort orphanScanPort; + private final CleanupQueuePort cleanupQueue; + private final FileAccessPolicyPort accessPolicy; + private final AdminAudit audit; + private final TransactionPort transactions; + + public ReconcileOrphansApplicationUseCase( + OrphanScanPort orphanScanPort, + CleanupQueuePort cleanupQueue, + FileAccessPolicyPort accessPolicy, + AdminAudit audit, + TransactionPort transactions) { + this.orphanScanPort = Objects.requireNonNull(orphanScanPort, "orphanScanPort"); + this.cleanupQueue = Objects.requireNonNull(cleanupQueue, "cleanupQueue"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.audit = Objects.requireNonNull(audit, "audit"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public OrphanReconcileReport handle(OrphanReconcileCommand command) { + RequestContext context = command.context(); + accessPolicy.authorize(FileOperation.ADMIN_FORCE_DELETE, context.subject(), Optional.empty()); + List candidates = orphanScanPort.scan(AdminAudit.boundedLimit(command.limit())); + if (command.dryRun()) { + audit.record("orphans:reconcile", command.reasonCode(), context, true, "dry-run"); + return new OrphanReconcileReport(true, candidates, 0, 0, 0); + } + + int deleted = 0; + int mismatched = 0; + long reclaimed = 0; + for (OrphanObject candidate : candidates) { + if (!command.expectedFingerprints().contains(candidate.fingerprint())) { + mismatched++; + continue; + } + if (reclaimed + candidate.sizeBytes() > command.maxBytes()) { + break; + } + if (orphanScanPort.deleteIfFingerprintMatches( + candidate.contentKey(), candidate.fingerprint())) { + // Retirement moved the object to quarantine; the durable record of that intent is queued + // immediately after. Without it a node that dies here leaves an object nobody is looking + // for, in an area nothing scans. + transactions.inWrite( + () -> cleanupQueue.enqueue(CleanupRequest.forOrphan(candidate.contentKey()))); + deleted++; + reclaimed += candidate.sizeBytes(); + } else { + mismatched++; + } + } + audit.record("orphans:reconcile", command.reasonCode(), context, true, "apply"); + return new OrphanReconcileReport(false, candidates, deleted, mismatched, reclaimed); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReverifyFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReverifyFileApplicationUseCase.java new file mode 100644 index 00000000..e9dec0c1 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ReverifyFileApplicationUseCase.java @@ -0,0 +1,79 @@ +package dev.caskeleton.application.fileserver.admin; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.port.in.ReverifyFileCommand; +import dev.caskeleton.application.fileserver.port.in.ReverifyFileUseCase; +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** Sends a quarantined file back to verification. */ +@RequiresPermission("file:admin") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + crossTenantAdmin = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class ReverifyFileApplicationUseCase implements ReverifyFileUseCase { + + private final FileMetadataPort metadataStore; + private final FileAccessPolicyPort accessPolicy; + private final AdminAudit audit; + private final TransactionPort transactions; + + public ReverifyFileApplicationUseCase( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + AdminAudit audit, + TransactionPort transactions) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.audit = Objects.requireNonNull(audit, "audit"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public FileView handle(ReverifyFileCommand command) { + RequestContext context = command.context(); + FileId fileId = command.fileId(); + accessPolicy.authorize(FileOperation.ADMIN_REVERIFY, context.subject(), Optional.empty()); + FileRecord record = FileRecords.require(metadataStore, fileId); + if (record.state() != FileState.QUARANTINED) { + audit.record("files:reverify", "REVERIFY_REJECTED", context, false, fileId.canonicalText()); + throw new FileserverException( + "only a quarantined file can be re-verified", + FileserverFailureContext.forFileState( + FileserverErrorCode.FILE_NOT_READY, fileId, record.state(), false)); + } + FileRecord verifying = + transactions.inWrite( + () -> + metadataStore.transition( + record.fileId(), + record.version(), + FileState.QUARANTINED, + FileState.VERIFYING, + FileRecordMutation.none())); + audit.record("files:reverify", "OPERATOR_REVERIFY", context, true, fileId.canonicalText()); + return FileView.of(verifying.toDescriptor()); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileRecords.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileRecords.java new file mode 100644 index 00000000..57d3acb7 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/metadata/FileRecords.java @@ -0,0 +1,53 @@ +package dev.caskeleton.application.fileserver.api.metadata; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; + +/** + * The two record checks every file operation starts with. + * + *

    Each operation used to carry its own copy of both, one per service; with one use case per + * operation that would have been a copy per use case, and a copy is where the refusal a client sees + * starts to differ between operations that should answer alike. + */ +public final class FileRecords { + + private FileRecords() {} + + /** + * The record of {@code fileId}, or the not-found refusal. + * + * @param metadata where records live + * @param fileId the file + * @return the record + * @throws FileNotFoundException when no record exists + */ + public static FileRecord require(FileMetadataPort metadata, FileId fileId) { + return metadata + .find(fileId) + .orElseThrow( + () -> + new FileNotFoundException( + "file record does not exist", + FileserverFailureContext.forFile( + FileserverErrorCode.FILE_NOT_FOUND, fileId, false))); + } + + /** + * Refuses a record that is not in a publicly readable state. + * + * @param record the record + * @throws FileserverException {@code FILE_NOT_READY}, retryable, otherwise + */ + public static void requireReadable(FileRecord record) { + if (!record.state().isPubliclyReadable()) { + throw new FileserverException( + "file is not in a publicly readable state", + FileserverFailureContext.forFileState( + FileserverErrorCode.FILE_NOT_READY, record.fileId(), record.state(), true)); + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileVerifier.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileVerifier.java deleted file mode 100644 index 773365c5..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/security/FileVerifier.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.application.fileserver.api.security; - -import java.util.concurrent.CompletionStage; - -/** - * One step of the verification pipeline. - * - *

    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 verify(VerificationRequest request); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DefaultDownloadApplicationService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DefaultDownloadApplicationService.java deleted file mode 100644 index 003f28f7..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DefaultDownloadApplicationService.java +++ /dev/null @@ -1,149 +0,0 @@ -package dev.caskeleton.application.fileserver.download; - -import dev.caskeleton.application.fileserver.api.ByteRange; -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; -import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; -import dev.caskeleton.application.fileserver.api.error.FileserverException; -import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; -import dev.caskeleton.application.fileserver.api.metadata.FileRecord; -import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; -import dev.caskeleton.application.fileserver.api.security.FileOperation; -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.observability.FileserverMetricsPort; -import dev.caskeleton.application.fileserver.observability.SizeBucket; -import dev.caskeleton.application.fileserver.upload.FileView; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; -import java.util.Optional; - -/** - * Authorizes download access and exposes immutable content facts. - * - *

    HTTP conditional requests, range parsing, status selection and response headers deliberately - * do not live here. The application proves the file exists, is readable and authorized; an inbound - * transport may then derive its wire response before opening content. - */ -public final class DefaultDownloadApplicationService implements DownloadApplicationService { - - private final FileMetadataPort metadataStore; - private final DownloadContentPort contentGateway; - private final FileAccessPolicyPort accessPolicy; - private final Optional zeroCopyGateway; - private final FileserverMetricsPort metrics; - - public DefaultDownloadApplicationService( - FileMetadataPort metadataStore, - DownloadContentPort contentGateway, - FileAccessPolicyPort accessPolicy) { - this( - metadataStore, - contentGateway, - accessPolicy, - Optional.empty(), - FileserverMetricsPort.noop()); - } - - public DefaultDownloadApplicationService( - FileMetadataPort metadataStore, - DownloadContentPort contentGateway, - FileAccessPolicyPort accessPolicy, - Optional zeroCopyGateway, - FileserverMetricsPort metrics) { - this.metadataStore = metadataStore; - this.contentGateway = contentGateway; - this.accessPolicy = accessPolicy; - this.zeroCopyGateway = zeroCopyGateway; - this.metrics = metrics; - } - - @Override - public FileView describeFile(FileId fileId, RequestContext context) { - FileRecord record = requireRecord(fileId); - accessPolicy.authorize( - FileOperation.READ_METADATA, context.subject(), Optional.of(record.toDescriptor())); - return FileView.of(record.toDescriptor()); - } - - @Override - public DownloadDescriptor describe(DownloadRequest request, RequestContext context) { - FileRecord record = requireRecord(request.fileId()); - accessPolicy.authorize( - FileOperation.DOWNLOAD, context.subject(), Optional.of(record.toDescriptor())); - requireReadable(record); - - FileRepresentation representation = - new FileRepresentation( - record.sha256().orElseThrow(DefaultDownloadApplicationService::readyWithoutValidator), - record - .publishedAt() - .orElseThrow(DefaultDownloadApplicationService::readyWithoutValidator), - record - .actualSize() - .orElseThrow(DefaultDownloadApplicationService::readyWithoutValidator), - record.verifiedMediaType().orElse("application/octet-stream")); - - return new DownloadDescriptor( - record.fileId(), - representation, - record.contentKey().orElseThrow(DefaultDownloadApplicationService::readyWithoutKey), - new SanitizedFilename(record.originalName())); - } - - @Override - public ReadableByteChannel openContent(DownloadDescriptor descriptor, ByteRange range) { - return contentGateway.openRead(descriptor.contentKey(), range); - } - - @Override - public ZeroCopyTransferResult transferContent( - DownloadDescriptor descriptor, ByteRange range, WritableByteChannel sink) { - ZeroCopyTransferResult result = - zeroCopyGateway - .map(gateway -> gateway.transferTo(descriptor.contentKey(), range, sink)) - .orElseGet(ZeroCopyTransferResult::notStarted); - String transferShape = - range.startInclusive() == 0 && range.length() == descriptor.representation().length() - ? "full" - : "partial"; - metrics.recordDownload( - "zero-copy", - transferShape, - result.outcome().name().toLowerCase(java.util.Locale.ROOT), - SizeBucket.of(range.length()), - java.time.Duration.ZERO, - result.transferredBytes()); - return result; - } - - private FileRecord requireRecord(FileId fileId) { - return metadataStore - .find(fileId) - .orElseThrow( - () -> - new FileNotFoundException( - "file record does not exist", - FileserverFailureContext.forFile( - FileserverErrorCode.FILE_NOT_FOUND, fileId, false))); - } - - private static void requireReadable(FileRecord record) { - if (!record.state().isPubliclyReadable()) { - throw new FileserverException( - "file is not in a publicly readable state", - FileserverFailureContext.forFileState( - FileserverErrorCode.FILE_NOT_READY, record.fileId(), record.state(), true)); - } - } - - private static IllegalStateException readyWithoutKey() { - return new IllegalStateException("READY record has no content key"); - } - - private static IllegalStateException readyWithoutValidator() { - return new IllegalStateException("READY record has no size, digest, or publication instant"); - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DescribeFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DescribeFileApplicationUseCase.java new file mode 100644 index 00000000..ff8a1f93 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DescribeFileApplicationUseCase.java @@ -0,0 +1,56 @@ +package dev.caskeleton.application.fileserver.download; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.DescribeFileQuery; +import dev.caskeleton.application.fileserver.port.in.DescribeFileUseCase; +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** + * Describes one file's metadata. + * + *

    {@code file:read} is the role check; {@link FileAccessPolicyPort} still decides whether this + * caller owns this file. + */ +@RequiresPermission("file:read") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.READ_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class DescribeFileApplicationUseCase implements DescribeFileUseCase { + + private final FileMetadataPort metadataStore; + private final FileAccessPolicyPort accessPolicy; + private final TransactionPort transactions; + + public DescribeFileApplicationUseCase( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public FileView handle(DescribeFileQuery query) { + FileRecord record = + transactions.inRead(() -> FileRecords.require(metadataStore, query.fileId())); + accessPolicy.authorize( + FileOperation.READ_METADATA, query.context().subject(), Optional.of(record.toDescriptor())); + return FileView.of(record.toDescriptor()); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadApplicationService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadApplicationService.java deleted file mode 100644 index 3d44cc28..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadApplicationService.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.application.fileserver.download; - -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.upload.FileView; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; - -/** - * The download half of the public application surface. - * - *

    {@link #describe} authorizes, requires READY, and evaluates validators and Range without - * touching content; only {@link #openContent} and {@link #transferContent} reach storage. A - * transport that answers {@code 304}, {@code 412}, or {@code 416} therefore never opens a byte. - */ -public interface DownloadApplicationService { - - /** Public metadata for {@code GET /v1/files/{fileId}}. */ - FileView describeFile(FileId fileId, RequestContext context); - - DownloadDescriptor describe(DownloadRequest request, RequestContext context); - - ReadableByteChannel openContent(DownloadDescriptor descriptor, ByteRange range); - - /** - * Asks storage to write the region directly into {@code sink}. - * - *

    Both this and {@link #openContent} start from an already-decided descriptor, so taking the - * fast path can never skip authorization or the READY gate. A {@code false} answer means the - * transport should stream instead; it is not an error and carries no response consequence. - */ - ZeroCopyTransferResult transferContent( - DownloadDescriptor descriptor, ByteRange range, WritableByteChannel sink); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadRequest.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadRequest.java deleted file mode 100644 index fa734c3e..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/DownloadRequest.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.application.fileserver.download; - -import dev.caskeleton.application.fileserver.api.FileId; -import java.util.Objects; - -/** Transport-neutral request to authorize and describe one readable file. */ -public record DownloadRequest(FileId fileId) { - - public DownloadRequest { - Objects.requireNonNull(fileId, "fileId"); - } - - public static DownloadRequest of(FileId fileId) { - return new DownloadRequest(fileId); - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/OpenDownloadContentApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/OpenDownloadContentApplicationUseCase.java new file mode 100644 index 00000000..a8e71b51 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/OpenDownloadContentApplicationUseCase.java @@ -0,0 +1,41 @@ +package dev.caskeleton.application.fileserver.download; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentQuery; +import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentUseCase; +import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.nio.channels.ReadableByteChannel; +import java.util.Objects; + +/** + * Opens the published bytes a prepared download describes. + * + *

    The descriptor is the authorization: only {@link PrepareDownloadUseCase} produces one, after + * the access policy allowed the read. The permission is checked again anyway, on the thread that + * streams, so a descriptor that outlived its caller's authority opens nothing. + */ +@RequiresPermission("file:read") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class OpenDownloadContentApplicationUseCase implements OpenDownloadContentUseCase { + + private final DownloadContentPort contentGateway; + + public OpenDownloadContentApplicationUseCase(DownloadContentPort contentGateway) { + this.contentGateway = Objects.requireNonNull(contentGateway, "contentGateway"); + } + + @Override + public ReadableByteChannel handle(OpenDownloadContentQuery query) { + return contentGateway.openRead(query.descriptor().contentKey(), query.byteRange()); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/PrepareDownloadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/PrepareDownloadApplicationUseCase.java new file mode 100644 index 00000000..32ece7ac --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/PrepareDownloadApplicationUseCase.java @@ -0,0 +1,82 @@ +package dev.caskeleton.application.fileserver.download; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.SanitizedFilename; +import dev.caskeleton.application.fileserver.api.transfer.FileRepresentation; +import dev.caskeleton.application.fileserver.port.in.PrepareDownloadQuery; +import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** + * Authorizes a download and describes the representation it will serve. + * + *

    {@code file:read} is the role check; {@link FileAccessPolicyPort} still decides whether this + * caller owns this file. + */ +@RequiresPermission("file:read") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.READ_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class PrepareDownloadApplicationUseCase implements PrepareDownloadUseCase { + + private final FileMetadataPort metadataStore; + private final FileAccessPolicyPort accessPolicy; + private final TransactionPort transactions; + + public PrepareDownloadApplicationUseCase( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public DownloadDescriptor handle(PrepareDownloadQuery query) { + FileRecord record = + transactions.inRead(() -> FileRecords.require(metadataStore, query.fileId())); + accessPolicy.authorize( + FileOperation.DOWNLOAD, query.context().subject(), Optional.of(record.toDescriptor())); + FileRecords.requireReadable(record); + + FileRepresentation representation = + new FileRepresentation( + record.sha256().orElseThrow(PrepareDownloadApplicationUseCase::readyWithoutValidator), + record + .publishedAt() + .orElseThrow(PrepareDownloadApplicationUseCase::readyWithoutValidator), + record + .actualSize() + .orElseThrow(PrepareDownloadApplicationUseCase::readyWithoutValidator), + record.verifiedMediaType().orElse("application/octet-stream")); + + return new DownloadDescriptor( + record.fileId(), + representation, + record.contentKey().orElseThrow(PrepareDownloadApplicationUseCase::readyWithoutKey), + new SanitizedFilename(record.originalName())); + } + + private static IllegalStateException readyWithoutKey() { + return new IllegalStateException("READY record has no content key"); + } + + private static IllegalStateException readyWithoutValidator() { + return new IllegalStateException("READY record has no size, digest, or publication instant"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/TransferDownloadContentApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/TransferDownloadContentApplicationUseCase.java new file mode 100644 index 00000000..2279fea8 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/download/TransferDownloadContentApplicationUseCase.java @@ -0,0 +1,64 @@ +package dev.caskeleton.application.fileserver.download; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.ByteRange; +import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; +import dev.caskeleton.application.fileserver.observability.SizeBucket; +import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentQuery; +import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.time.Duration; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; + +/** + * Hands a prepared download to the storage for a kernel-level transfer, when it can. + * + *

    A storage without zero copy answers {@link ZeroCopyTransferResult#notStarted()}, and the + * transport streams instead; the response is byte-identical either way. + */ +@RequiresPermission("file:read") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class TransferDownloadContentApplicationUseCase implements TransferDownloadContentUseCase { + + private final Optional zeroCopyGateway; + private final FileserverMetricsPort metrics; + + public TransferDownloadContentApplicationUseCase( + Optional zeroCopyGateway, FileserverMetricsPort metrics) { + this.zeroCopyGateway = Objects.requireNonNull(zeroCopyGateway, "zeroCopyGateway"); + this.metrics = Objects.requireNonNull(metrics, "metrics"); + } + + @Override + public ZeroCopyTransferResult handle(TransferDownloadContentQuery query) { + DownloadDescriptor descriptor = query.descriptor(); + ByteRange range = query.byteRange(); + ZeroCopyTransferResult result = + zeroCopyGateway + .map(gateway -> gateway.transferTo(descriptor.contentKey(), range, query.sink())) + .orElseGet(ZeroCopyTransferResult::notStarted); + String transferShape = + range.startInclusive() == 0 && range.length() == descriptor.representation().length() + ? "full" + : "partial"; + metrics.recordDownload( + "zero-copy", + transferShape, + result.outcome().name().toLowerCase(Locale.ROOT), + SizeBucket.of(range.length()), + Duration.ZERO, + result.transferredBytes()); + return result; + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/ContentPreconditions.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/ContentPreconditions.java new file mode 100644 index 00000000..f37ca47e --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/ContentPreconditions.java @@ -0,0 +1,27 @@ +package dev.caskeleton.application.fileserver.lifecycle; + +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import java.util.Optional; + +/** The content-version precondition delete, copy and move all honour. */ +final class ContentPreconditions { + + private ContentPreconditions() {} + + /** Enforces a transport-neutral content-version precondition over the immutable SHA-256. */ + static void requireDigestMatches(FileRecord record, Optional expectedSha256) { + if (expectedSha256.isEmpty()) { + return; + } + if (expectedSha256.orElseThrow().equals(record.sha256().orElse(null))) { + return; + } + throw new FileserverException( + "file validator does not match the caller's precondition", + FileserverFailureContext.forFileState( + FileserverErrorCode.PRECONDITION_FAILED, record.fileId(), record.state(), false)); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java new file mode 100644 index 00000000..71bf38fa --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileApplicationUseCase.java @@ -0,0 +1,172 @@ +package dev.caskeleton.application.fileserver.lifecycle; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.content.StoredContent; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.api.security.SanitizedFilename; +import dev.caskeleton.application.fileserver.port.in.CopyFileCommand; +import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase; +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.util.Objects; +import java.util.Optional; + +/** Copies a readable file into a new file the caller owns. */ +@RequiresPermission("file:copy") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class CopyFileApplicationUseCase implements CopyFileUseCase { + + private final FileMetadataPort metadataStore; + private final CopyContentPort copyGateway; + private final FileAccessPolicyPort accessPolicy; + private final OriginalFilenamePolicy filenamePolicy; + private final UploadIdentifierPort identifierFactory; + private final TransactionPort transactions; + private final Clock clock; + + public CopyFileApplicationUseCase( + FileMetadataPort metadataStore, + CopyContentPort copyGateway, + FileAccessPolicyPort accessPolicy, + OriginalFilenamePolicy filenamePolicy, + UploadIdentifierPort identifierFactory, + TransactionPort transactions, + Clock clock) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.copyGateway = Objects.requireNonNull(copyGateway, "copyGateway"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.filenamePolicy = Objects.requireNonNull(filenamePolicy, "filenamePolicy"); + this.identifierFactory = Objects.requireNonNull(identifierFactory, "identifierFactory"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public FileView handle(CopyFileCommand command) { + RequestContext context = command.context(); + FileRecord source = FileRecords.require(metadataStore, command.sourceFileId()); + accessPolicy.authorize( + FileOperation.COPY, context.subject(), Optional.of(source.toDescriptor())); + ContentPreconditions.requireDigestMatches(source, command.expectedSha256()); + FileRecords.requireReadable(source); + + SanitizedFilename filename = + filenamePolicy.sanitize(command.targetFilename().orElse(source.originalName())); + FileId targetId = identifierFactory.newFileId(); + FileRecord target = + transactions.inWrite( + () -> + metadataStore.insert( + new FileRecordDraft( + targetId, + command.targetNamespace(), + filename.value(), + source.verifiedMediaType().or(source::claimedMediaType), + source.actualSize(), + // The copy belongs to whoever made it, not to the source's owner. + context.subject().asOwner()))); + + StoredContent copied; + try { + copied = + copyGateway.copyCreateOnly( + source.contentKey().orElseThrow(CopyFileApplicationUseCase::readyWithoutKey), + command.targetNamespace()); + } catch (RuntimeException failure) { + // The target may exist as a partial object; no rollback is promised, so it is queued for the + // cleanup worker instead of being left for an orphan scan to find much later. + failRecord(target, "COPY_FAILED"); + throw failure; + } + return FileView.of(publish(target, copied).toDescriptor()); + } + + /** Walks the copied target to READY through the same edges an upload would take. */ + private FileRecord publish(FileRecord target, StoredContent copied) { + // Four hops, one boundary. The intermediate states exist to satisfy the transition table, not + // to be observable; a copy that stalled on one of them would look like a stuck upload. + return transactions.inWrite(() -> publishSteps(target, copied)); + } + + private FileRecord publishSteps(FileRecord target, StoredContent copied) { + FileRecord uploading = + metadataStore.transition( + target.fileId(), + target.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()); + FileRecord uploaded = + metadataStore.transition( + uploading.fileId(), + uploading.version(), + FileState.UPLOADING, + FileState.UPLOADED, + FileRecordMutation.uploaded(copied.size(), copied.sha256())); + FileRecord verifying = + metadataStore.transition( + uploaded.fileId(), + uploaded.version(), + FileState.UPLOADED, + FileState.VERIFYING, + FileRecordMutation.none()); + return metadataStore.transition( + verifying.fileId(), + verifying.version(), + FileState.VERIFYING, + FileState.READY, + FileRecordMutation.publishAt( + copied.contentKey(), copied.size(), copied.sha256(), clock.instant())); + } + + /** + * Moves a freshly-created target to FAILED. + * + *

    The transition table has no direct {@code CREATED -> FAILED} edge, so the record takes the + * one path it permits, through UPLOADING. + */ + private void failRecord(FileRecord record, String reasonCode) { + transactions.inWrite( + () -> { + FileRecord uploading = + metadataStore.transition( + record.fileId(), + record.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()); + metadataStore.transition( + uploading.fileId(), + uploading.version(), + FileState.UPLOADING, + FileState.FAILED, + FileRecordMutation.failure(reasonCode)); + }); + } + + private static IllegalStateException readyWithoutKey() { + return new IllegalStateException("READY record has no content key"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DefaultFileLifecycleService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DefaultFileLifecycleService.java deleted file mode 100644 index d8dbac4f..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DefaultFileLifecycleService.java +++ /dev/null @@ -1,270 +0,0 @@ -package dev.caskeleton.application.fileserver.lifecycle; - -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.FileState; -import dev.caskeleton.application.fileserver.api.StorageNamespace; -import dev.caskeleton.application.fileserver.api.content.StoredContent; -import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; -import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; -import dev.caskeleton.application.fileserver.api.error.FileserverException; -import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; -import dev.caskeleton.application.fileserver.api.metadata.FileRecord; -import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; -import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; -import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; -import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; -import dev.caskeleton.application.fileserver.api.security.FileOperation; -import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.api.security.SanitizedFilename; -import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; -import dev.caskeleton.application.fileserver.cleanup.FileRetirement; -import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; -import dev.caskeleton.application.fileserver.upload.FileView; -import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.util.Optional; - -/** - * Logical-first delete, copy, and move. - * - *

    Delete transitions the record to DELETING before anything physical is scheduled, so a - * deleted file stops being downloadable the instant the metadata commits — even if the cleanup - * worker is hours behind. Copy is create-only and queues its partial target for cleanup rather than - * promising a rollback the filesystem cannot give. Move rewrites one metadata column and never - * touches the immutable object. - */ -public final class DefaultFileLifecycleService implements FileLifecycleService { - - private final FileMetadataPort metadataStore; - private final CopyContentPort copyGateway; - private final FileAccessPolicyPort accessPolicy; - private final OriginalFilenamePolicy filenamePolicy; - private final UploadIdentifierPort identifierFactory; - private final TransactionPort transactions; - private final Clock clock; - private final FileRetirement retirement; - private final UploadSessionPort sessionStore; - private final StagingUploadLocatorPort stagingLocator; - - public DefaultFileLifecycleService( - FileMetadataPort metadataStore, - CopyContentPort copyGateway, - FileAccessPolicyPort accessPolicy, - OriginalFilenamePolicy filenamePolicy, - CleanupQueuePort cleanupQueue, - UploadSessionPort sessionStore, - StagingUploadLocatorPort stagingLocator, - UploadIdentifierPort identifierFactory, - TransactionPort transactions, - Clock clock) { - this.metadataStore = metadataStore; - this.copyGateway = copyGateway; - this.accessPolicy = accessPolicy; - this.filenamePolicy = filenamePolicy; - this.identifierFactory = identifierFactory; - this.transactions = transactions; - this.clock = clock; - this.retirement = new FileRetirement(metadataStore, cleanupQueue); - this.sessionStore = sessionStore; - this.stagingLocator = stagingLocator; - } - - @Override - public DeleteOutcome delete( - FileId fileId, Optional expectedSha256, RequestContext context) { - FileRecord record = requireRecord(fileId); - accessPolicy.authorize( - FileOperation.DELETE, context.subject(), Optional.of(record.toDescriptor())); - requireDigestMatches(record, expectedSha256); - - if (record.state() == FileState.DELETED) { - return new DeleteOutcome(fileId, false); - } - requireDeletable(record); - - // One boundary for the whole decision: a record that reached DELETING without either its - // terminal transition or a queued reclamation would be unreachable and never collected. - return transactions.inWrite( - () -> - new DeleteOutcome( - fileId, - retirement.retireWithUnfinishedUpload(record, sessionStore, stagingLocator))); - } - - @Override - public FileView copy(CopyFileCommand command, RequestContext context) { - FileRecord source = requireRecord(command.sourceFileId()); - accessPolicy.authorize( - FileOperation.COPY, context.subject(), Optional.of(source.toDescriptor())); - requireDigestMatches(source, command.expectedSha256()); - requireReadable(source); - - SanitizedFilename filename = - filenamePolicy.sanitize(command.targetFilename().orElse(source.originalName())); - FileId targetId = identifierFactory.newFileId(); - FileRecord target = - transactions.inWrite( - () -> - metadataStore.insert( - new FileRecordDraft( - targetId, - command.targetNamespace(), - filename.value(), - source.verifiedMediaType().or(source::claimedMediaType), - source.actualSize(), - // The copy belongs to whoever made it, not to the source's owner. - context.subject().asOwner()))); - - StoredContent copied; - try { - copied = - copyGateway.copyCreateOnly( - source.contentKey().orElseThrow(DefaultFileLifecycleService::readyWithoutKey), - command.targetNamespace()); - } catch (RuntimeException failure) { - // The target may exist as a partial object; no rollback is promised, so it is queued for the - // cleanup worker instead of being left for an orphan scan to find much later. - failRecord(target, "COPY_FAILED"); - throw failure; - } - return FileView.of(publish(target, copied).toDescriptor()); - } - - @Override - public FileView move( - FileId fileId, - StorageNamespace targetNamespace, - Optional expectedSha256, - RequestContext context) { - FileRecord record = requireRecord(fileId); - accessPolicy.authorize( - FileOperation.MOVE, context.subject(), Optional.of(record.toDescriptor())); - requireDigestMatches(record, expectedSha256); - requireReadable(record); - - return FileView.of( - transactions - .inWrite(() -> metadataStore.relocate(fileId, record.version(), targetNamespace)) - .toDescriptor()); - } - - /** Walks the copied target to READY through the same edges an upload would take. */ - private FileRecord publish(FileRecord target, StoredContent copied) { - // Four hops, one boundary. The intermediate states exist to satisfy the transition table, not - // to be observable; a copy that stalled on one of them would look like a stuck upload. - return transactions.inWrite(() -> publishSteps(target, copied)); - } - - private FileRecord publishSteps(FileRecord target, StoredContent copied) { - FileRecord uploading = - metadataStore.transition( - target.fileId(), - target.version(), - FileState.CREATED, - FileState.UPLOADING, - FileRecordMutation.none()); - FileRecord uploaded = - metadataStore.transition( - uploading.fileId(), - uploading.version(), - FileState.UPLOADING, - FileState.UPLOADED, - FileRecordMutation.uploaded(copied.size(), copied.sha256())); - FileRecord verifying = - metadataStore.transition( - uploaded.fileId(), - uploaded.version(), - FileState.UPLOADED, - FileState.VERIFYING, - FileRecordMutation.none()); - return metadataStore.transition( - verifying.fileId(), - verifying.version(), - FileState.VERIFYING, - FileState.READY, - FileRecordMutation.publishAt( - copied.contentKey(), copied.size(), copied.sha256(), clock.instant())); - } - - /** - * Moves a freshly-created target to FAILED. - * - *

    The transition table has no direct {@code CREATED -> FAILED} edge, so the record takes the - * one path it permits, through UPLOADING. - */ - private void failRecord(FileRecord record, String reasonCode) { - transactions.inWrite( - () -> { - FileRecord uploading = - metadataStore.transition( - record.fileId(), - record.version(), - FileState.CREATED, - FileState.UPLOADING, - FileRecordMutation.none()); - metadataStore.transition( - uploading.fileId(), - uploading.version(), - FileState.UPLOADING, - FileState.FAILED, - FileRecordMutation.failure(reasonCode)); - }); - } - - /** Enforces a transport-neutral content-version precondition over the immutable SHA-256. */ - private static void requireDigestMatches(FileRecord record, Optional expectedSha256) { - if (expectedSha256.isEmpty()) { - return; - } - if (expectedSha256.orElseThrow().equals(record.sha256().orElse(null))) { - return; - } - throw new FileserverException( - "file validator does not match the caller's precondition", - FileserverFailureContext.forFileState( - FileserverErrorCode.PRECONDITION_FAILED, record.fileId(), record.state(), false)); - } - - /** - * Refuses a delete from a state that has no DELETING edge. - * - *

    CREATED and VERIFYING are transient states owned by the upload and verification pipelines. - * Forcing them into DELETING would either invent a transition the state machine does not have, or - * mislabel the file as verifier-rejected. The caller is told to retry once the state settles. - */ - private static void requireDeletable(FileRecord record) { - if (record.state() == FileState.CREATED || record.state() == FileState.VERIFYING) { - throw new FileserverException( - "file is in a transient state that cannot be deleted yet", - FileserverFailureContext.forFileState( - FileserverErrorCode.FILE_NOT_READY, record.fileId(), record.state(), true)); - } - } - - private static void requireReadable(FileRecord record) { - if (!record.state().isPubliclyReadable()) { - throw new FileserverException( - "file is not in a publicly readable state", - FileserverFailureContext.forFileState( - FileserverErrorCode.FILE_NOT_READY, record.fileId(), record.state(), true)); - } - } - - private FileRecord requireRecord(FileId fileId) { - return metadataStore - .find(fileId) - .orElseThrow( - () -> - new FileNotFoundException( - "file record does not exist", - FileserverFailureContext.forFile( - FileserverErrorCode.FILE_NOT_FOUND, fileId, false))); - } - - private static IllegalStateException readyWithoutKey() { - return new IllegalStateException("READY record has no content key"); - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DeleteFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DeleteFileApplicationUseCase.java new file mode 100644 index 00000000..fde1b6df --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/DeleteFileApplicationUseCase.java @@ -0,0 +1,102 @@ +package dev.caskeleton.application.fileserver.lifecycle; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.FileRetirement; +import dev.caskeleton.application.fileserver.port.in.DeleteFileCommand; +import dev.caskeleton.application.fileserver.port.in.DeleteFileUseCase; +import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** + * Deletes a file: it stops being reachable and its content is queued for reclamation. + * + *

    {@code file:delete} is the role check; {@link FileAccessPolicyPort} still decides whether this + * caller owns this file, so the permission never reaches somebody else's. + */ +@RequiresPermission("file:delete") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class DeleteFileApplicationUseCase implements DeleteFileUseCase { + + private final FileMetadataPort metadataStore; + private final FileAccessPolicyPort accessPolicy; + private final FileRetirement retirement; + private final UploadSessionPort sessionStore; + private final StagingUploadLocatorPort stagingLocator; + private final TransactionPort transactions; + + public DeleteFileApplicationUseCase( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + CleanupQueuePort cleanupQueue, + UploadSessionPort sessionStore, + StagingUploadLocatorPort stagingLocator, + TransactionPort transactions) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.retirement = new FileRetirement(metadataStore, cleanupQueue); + this.sessionStore = Objects.requireNonNull(sessionStore, "sessionStore"); + this.stagingLocator = Objects.requireNonNull(stagingLocator, "stagingLocator"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public DeleteOutcome handle(DeleteFileCommand command) { + FileId fileId = command.fileId(); + FileRecord record = FileRecords.require(metadataStore, fileId); + accessPolicy.authorize( + FileOperation.DELETE, command.context().subject(), Optional.of(record.toDescriptor())); + ContentPreconditions.requireDigestMatches(record, command.expectedSha256()); + + if (record.state() == FileState.DELETED) { + return new DeleteOutcome(fileId, false); + } + requireDeletable(record); + + // One boundary for the whole decision: a record that reached DELETING without either its + // terminal transition or a queued reclamation would be unreachable and never collected. + return transactions.inWrite( + () -> + new DeleteOutcome( + fileId, + retirement.retireWithUnfinishedUpload(record, sessionStore, stagingLocator))); + } + + /** + * Refuses a delete from a state that has no DELETING edge. + * + *

    CREATED and VERIFYING are transient states owned by the upload and verification pipelines. + * Forcing them into DELETING would either invent a transition the state machine does not have, or + * mislabel the file as verifier-rejected. The caller is told to retry once the state settles. + */ + private static void requireDeletable(FileRecord record) { + if (record.state() == FileState.CREATED || record.state() == FileState.VERIFYING) { + throw new FileserverException( + "file is in a transient state that cannot be deleted yet", + FileserverFailureContext.forFileState( + FileserverErrorCode.FILE_NOT_READY, record.fileId(), record.state(), true)); + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleService.java deleted file mode 100644 index a2fdbbff..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleService.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.application.fileserver.lifecycle; - -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.StorageNamespace; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.upload.FileView; -import java.util.Optional; - -/** - * Delete, copy, and move — the inbound port the transport reaches them through. - * - *

    All three are logical-first: the metadata record decides reachability, and physical work is - * deferred to the cleanup worker. That ordering is what makes a delete take effect immediately even - * when the filesystem is slow or briefly unavailable. - * - *

    An interface with one implementation, kept on purpose: an inbound adapter may depend only on a - * port, never on a concrete application service ({@code - * INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES}). - */ -public interface FileLifecycleService { - - DeleteOutcome delete(FileId fileId, Optional expectedSha256, RequestContext context); - - FileView copy(CopyFileCommand command, RequestContext context); - - FileView move( - FileId fileId, - StorageNamespace targetNamespace, - Optional expectedSha256, - RequestContext context); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java new file mode 100644 index 00000000..59605a19 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/MoveFileApplicationUseCase.java @@ -0,0 +1,59 @@ +package dev.caskeleton.application.fileserver.lifecycle; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.MoveFileCommand; +import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase; +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** Moves a readable file to another namespace. */ +@RequiresPermission("file:move") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class MoveFileApplicationUseCase implements MoveFileUseCase { + + private final FileMetadataPort metadataStore; + private final FileAccessPolicyPort accessPolicy; + private final TransactionPort transactions; + + public MoveFileApplicationUseCase( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions) { + this.metadataStore = Objects.requireNonNull(metadataStore, "metadataStore"); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public FileView handle(MoveFileCommand command) { + FileId fileId = command.fileId(); + FileRecord record = FileRecords.require(metadataStore, fileId); + accessPolicy.authorize( + FileOperation.MOVE, command.context().subject(), Optional.of(record.toDescriptor())); + ContentPreconditions.requireDigestMatches(record, command.expectedSha256()); + FileRecords.requireReadable(record); + + return FileView.of( + transactions + .inWrite( + () -> metadataStore.relocate(fileId, record.version(), command.targetNamespace())) + .toDescriptor()); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadCommand.java new file mode 100644 index 00000000..c933afb7 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadCommand.java @@ -0,0 +1,35 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.nio.channels.ReadableByteChannel; +import java.util.Objects; +import java.util.Optional; + +/** + * Append one chunk at the offset the client believes is committed. + * + * @param uploadId the open upload + * @param expectedOffset the offset the client believes is committed + * @param content the bytes to append; the caller owns and closes it + * @param contentLength the declared chunk length, or a negative value when unknown + * @param expectedChunkSha256 the client's digest of this chunk, if any + * @param context the caller + */ +public record AppendUploadCommand( + UploadId uploadId, + long expectedOffset, + ReadableByteChannel content, + long contentLength, + Optional expectedChunkSha256, + RequestContext context) + implements Command { + + public AppendUploadCommand { + Objects.requireNonNull(uploadId, "uploadId"); + Objects.requireNonNull(content, "content"); + Objects.requireNonNull(expectedChunkSha256, "expectedChunkSha256"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadUseCase.java new file mode 100644 index 00000000..1eba16ba --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/AppendUploadUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.AppendUploadResult; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Appends one chunk to an open upload under a writer lease. */ +public interface AppendUploadUseCase + extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadCommand.java new file mode 100644 index 00000000..d6717f2a --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadCommand.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.util.Objects; + +/** + * Cancel one upload. + * + * @param uploadId the upload + * @param context the caller + */ +public record CancelUploadCommand(UploadId uploadId, RequestContext context) implements Command { + + public CancelUploadCommand { + Objects.requireNonNull(uploadId, "uploadId"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadUseCase.java new file mode 100644 index 00000000..590d5eb6 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CancelUploadUseCase.java @@ -0,0 +1,6 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Cancels an upload: the record stops being reachable and its bytes are queued for removal. */ +public interface CancelUploadUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsCommand.java new file mode 100644 index 00000000..a1f15e75 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsCommand.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.util.Objects; + +/** + * Run one cleanup batch. + * + * @param maxItems the most queued items to process; capped by the use case + * @param maxBytes the byte budget of the batch + * @param context the operator + */ +public record CleanupUploadsCommand(int maxItems, long maxBytes, RequestContext context) + implements Command { + + public CleanupUploadsCommand { + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsUseCase.java new file mode 100644 index 00000000..9e290d1e --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CleanupUploadsUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Runs one cleanup batch on an operator's request. */ +public interface CleanupUploadsUseCase + extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileCommand.java similarity index 50% rename from src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileCommand.java rename to src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileCommand.java index e0418f2f..902520fd 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/lifecycle/CopyFileCommand.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileCommand.java @@ -1,27 +1,34 @@ -package dev.caskeleton.application.fileserver.lifecycle; +package dev.caskeleton.application.fileserver.port.in; +import dev.caskeleton.application.command.Command; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.security.RequestContext; import java.util.Objects; import java.util.Optional; /** - * Intent to copy a READY file into a namespace. + * Copy one file. * - *

    {@code expectedSha256} is an optional immutable-content version asserted by the caller. - * Transport adapters translate their own validator syntax into this raw digest before invoking the - * use case. + * @param sourceFileId the file to copy + * @param targetNamespace where the copy goes + * @param targetFilename the copy's display name, if not the source's + * @param expectedSha256 the caller's content-version precondition, if any + * @param context the caller */ public record CopyFileCommand( FileId sourceFileId, StorageNamespace targetNamespace, Optional targetFilename, - Optional expectedSha256) { + Optional expectedSha256, + RequestContext context) + implements Command { public CopyFileCommand { Objects.requireNonNull(sourceFileId, "sourceFileId"); Objects.requireNonNull(targetNamespace, "targetNamespace"); Objects.requireNonNull(targetFilename, "targetFilename"); Objects.requireNonNull(expectedSha256, "expectedSha256"); + Objects.requireNonNull(context, "context"); } } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileUseCase.java new file mode 100644 index 00000000..1978c247 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CopyFileUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Copies a readable file into a new file the caller owns. */ +public interface CopyFileUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadCommand.java new file mode 100644 index 00000000..996c47d1 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadCommand.java @@ -0,0 +1,21 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; +import java.util.Objects; + +/** + * Open one upload for the caller. + * + * @param request what the client asked for + * @param context the caller + */ +public record CreateUploadCommand(CreateUploadRequest request, RequestContext context) + implements Command { + + public CreateUploadCommand { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadUseCase.java new file mode 100644 index 00000000..8e2c3ca0 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/CreateUploadUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.UploadSessionView; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Opens an upload: reserves quota, records the file and its session, and creates staging. */ +public interface CreateUploadUseCase + extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileCommand.java new file mode 100644 index 00000000..1a38c228 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileCommand.java @@ -0,0 +1,24 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.util.Objects; +import java.util.Optional; + +/** + * Delete one file. + * + * @param fileId the file + * @param expectedSha256 the caller's content-version precondition, if any + * @param context the caller + */ +public record DeleteFileCommand( + FileId fileId, Optional expectedSha256, RequestContext context) implements Command { + + public DeleteFileCommand { + Objects.requireNonNull(fileId, "fileId"); + Objects.requireNonNull(expectedSha256, "expectedSha256"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileUseCase.java new file mode 100644 index 00000000..dde889a3 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DeleteFileUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.lifecycle.DeleteOutcome; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Deletes a file: it stops being reachable and its content is queued for reclamation. */ +public interface DeleteFileUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileQuery.java new file mode 100644 index 00000000..2e5f6715 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileQuery.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * Read one file's metadata. + * + * @param fileId the file + * @param context the caller + */ +public record DescribeFileQuery(FileId fileId, RequestContext context) implements Query { + + public DescribeFileQuery { + Objects.requireNonNull(fileId, "fileId"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileUseCase.java new file mode 100644 index 00000000..258947b4 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/DescribeFileUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.usecase.QueryUseCase; + +/** Describes one file's metadata to a caller allowed to read it. */ +public interface DescribeFileUseCase extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadCommand.java new file mode 100644 index 00000000..1bf746bd --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadCommand.java @@ -0,0 +1,24 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest; +import java.util.Objects; + +/** + * Finalize one upload. + * + * @param uploadId the fully received upload + * @param request the client's finalization assertions + * @param context the caller + */ +public record FinalizeUploadCommand( + UploadId uploadId, FinalizeUploadRequest request, RequestContext context) implements Command { + + public FinalizeUploadCommand { + Objects.requireNonNull(uploadId, "uploadId"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadUseCase.java new file mode 100644 index 00000000..96b073e0 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/FinalizeUploadUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Verifies and publishes a fully received upload. */ +public interface FinalizeUploadUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteCommand.java similarity index 68% rename from src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteCommand.java rename to src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteCommand.java index 79cfc075..2130f620 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/ForceDeleteCommand.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteCommand.java @@ -1,6 +1,8 @@ -package dev.caskeleton.application.fileserver.admin; +package dev.caskeleton.application.fileserver.port.in; +import dev.caskeleton.application.command.Command; import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; import java.util.Objects; /** @@ -9,14 +11,20 @@ import java.util.Objects; *

    The reason is mandatory and the caller must hold the second, force-delete-specific authority. * A force delete that needed only the ordinary delete permission would make every operator able to * destroy content the lifecycle rules exist to protect. + * + * @param fileId the file + * @param reasonCode why, for the audit trail + * @param context the operator */ -public record ForceDeleteCommand(FileId fileId, String reasonCode) { +public record ForceDeleteCommand(FileId fileId, String reasonCode, RequestContext context) + implements Command { private static final int MINIMUM_REASON_LENGTH = 8; public ForceDeleteCommand { Objects.requireNonNull(fileId, "fileId"); Objects.requireNonNull(reasonCode, "reasonCode"); + Objects.requireNonNull(context, "context"); if (reasonCode.strip().length() < MINIMUM_REASON_LENGTH) { throw new IllegalArgumentException("force delete requires an explicit reason"); } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteFileUseCase.java new file mode 100644 index 00000000..dd131943 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ForceDeleteFileUseCase.java @@ -0,0 +1,6 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Removes a file on an operator's authority, bypassing the data-plane preconditions. */ +public interface ForceDeleteFileUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesQuery.java new file mode 100644 index 00000000..a7eb62d4 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesQuery.java @@ -0,0 +1,17 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * Read the runtime capabilities. + * + * @param context the operator + */ +public record GetRuntimeCapabilitiesQuery(RequestContext context) implements Query { + + public GetRuntimeCapabilitiesQuery { + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesUseCase.java new file mode 100644 index 00000000..7147a35b --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetRuntimeCapabilitiesUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.admin.RuntimeCapabilityReport; +import dev.caskeleton.application.usecase.QueryUseCase; + +/** Reports what the running storage supports to an operator. */ +public interface GetRuntimeCapabilitiesUseCase + extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthQuery.java new file mode 100644 index 00000000..91d204e2 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthQuery.java @@ -0,0 +1,17 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * Read storage health. + * + * @param context the operator + */ +public record GetStorageHealthQuery(RequestContext context) implements Query { + + public GetStorageHealthQuery { + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthUseCase.java new file mode 100644 index 00000000..3766c7f1 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetStorageHealthUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.admin.StorageHealthReport; +import dev.caskeleton.application.usecase.QueryUseCase; + +/** Reports the storage's health to an operator. */ +public interface GetStorageHealthUseCase + extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusQuery.java new file mode 100644 index 00000000..8d345174 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusQuery.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * Read where an open upload stands. + * + * @param uploadId the upload + * @param context the caller + */ +public record GetUploadStatusQuery(UploadId uploadId, RequestContext context) implements Query { + + public GetUploadStatusQuery { + Objects.requireNonNull(uploadId, "uploadId"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusUseCase.java new file mode 100644 index 00000000..6145b025 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/GetUploadStatusUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.UploadSessionView; +import dev.caskeleton.application.usecase.QueryUseCase; + +/** Reports the committed offset of an open upload; an ended upload answers gone. */ +public interface GetUploadStatusUseCase + extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsQuery.java new file mode 100644 index 00000000..3a8960e4 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsQuery.java @@ -0,0 +1,18 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * List incomplete uploads. + * + * @param limit the page size; capped by the use case + * @param context the operator + */ +public record ListIncompleteUploadsQuery(int limit, RequestContext context) implements Query { + + public ListIncompleteUploadsQuery { + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsUseCase.java new file mode 100644 index 00000000..474e2cbb --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListIncompleteUploadsUseCase.java @@ -0,0 +1,9 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.admin.IncompleteUploadView; +import dev.caskeleton.application.usecase.QueryUseCase; +import java.util.List; + +/** Lists uploads that expired before they finished. */ +public interface ListIncompleteUploadsUseCase + extends QueryUseCase> {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansQuery.java new file mode 100644 index 00000000..6456d0a9 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansQuery.java @@ -0,0 +1,18 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * List orphaned objects. + * + * @param limit the page size; capped by the use case + * @param context the operator + */ +public record ListOrphansQuery(int limit, RequestContext context) implements Query { + + public ListOrphansQuery { + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansUseCase.java new file mode 100644 index 00000000..f6e4156a --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ListOrphansUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.admin.OrphanObject; +import dev.caskeleton.application.usecase.QueryUseCase; +import java.util.List; + +/** Lists physical objects no record refers to. */ +public interface ListOrphansUseCase extends QueryUseCase> {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileCommand.java new file mode 100644 index 00000000..6e1ea6fb --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileCommand.java @@ -0,0 +1,31 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.util.Objects; +import java.util.Optional; + +/** + * Move one file. + * + * @param fileId the file + * @param targetNamespace where it moves + * @param expectedSha256 the caller's content-version precondition, if any + * @param context the caller + */ +public record MoveFileCommand( + FileId fileId, + StorageNamespace targetNamespace, + Optional expectedSha256, + RequestContext context) + implements Command { + + public MoveFileCommand { + Objects.requireNonNull(fileId, "fileId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(expectedSha256, "expectedSha256"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileUseCase.java new file mode 100644 index 00000000..cd66d6fd --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/MoveFileUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Moves a readable file to another namespace. */ +public interface MoveFileUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentQuery.java new file mode 100644 index 00000000..8a83759e --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentQuery.java @@ -0,0 +1,21 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.ByteRange; +import dev.caskeleton.application.fileserver.download.DownloadDescriptor; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * Open a range of a prepared download. + * + * @param descriptor what an authorized prepare returned + * @param byteRange the bytes to read + */ +public record OpenDownloadContentQuery(DownloadDescriptor descriptor, ByteRange byteRange) + implements Query { + + public OpenDownloadContentQuery { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(byteRange, "byteRange"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentUseCase.java new file mode 100644 index 00000000..10a7cb9f --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OpenDownloadContentUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.usecase.QueryUseCase; +import java.nio.channels.ReadableByteChannel; + +/** Opens the published bytes a prepared download describes. */ +public interface OpenDownloadContentUseCase + extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/OrphanReconcileCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OrphanReconcileCommand.java similarity index 61% rename from src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/OrphanReconcileCommand.java rename to src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OrphanReconcileCommand.java index f9575920..52d826fb 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/admin/OrphanReconcileCommand.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/OrphanReconcileCommand.java @@ -1,5 +1,7 @@ -package dev.caskeleton.application.fileserver.admin; +package dev.caskeleton.application.fileserver.port.in; +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.security.RequestContext; import java.util.List; import java.util.Objects; @@ -9,17 +11,27 @@ import java.util.Objects; *

    {@code dryRun} defaults to true at every layer above this record. An apply additionally has to * name the exact fingerprints it intends to remove and a byte budget, so a reconcile can never turn * into an unbounded mass delete driven by a stale scan. + * + * @param dryRun list only, remove nothing + * @param limit the most candidates to consider + * @param maxBytes the byte budget of an apply + * @param expectedFingerprints the exact objects an apply may remove + * @param reasonCode why, for the audit trail + * @param context the operator */ public record OrphanReconcileCommand( boolean dryRun, int limit, long maxBytes, List expectedFingerprints, - String reasonCode) { + String reasonCode, + RequestContext context) + implements Command { public OrphanReconcileCommand { Objects.requireNonNull(expectedFingerprints, "expectedFingerprints"); Objects.requireNonNull(reasonCode, "reasonCode"); + Objects.requireNonNull(context, "context"); if (limit < 1 || maxBytes < 1) { throw new IllegalArgumentException("limit and maxBytes must be positive"); } @@ -34,7 +46,8 @@ public record OrphanReconcileCommand( } /** Bounded dry run, the default and the only shape a caller can reach without opting in. */ - public static OrphanReconcileCommand dryRun(int limit) { - return new OrphanReconcileCommand(true, limit, Long.MAX_VALUE, List.of(), "ORPHAN_SCAN"); + public static OrphanReconcileCommand dryRun(int limit, RequestContext context) { + return new OrphanReconcileCommand( + true, limit, Long.MAX_VALUE, List.of(), "ORPHAN_SCAN", context); } } diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadQuery.java new file mode 100644 index 00000000..03458357 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadQuery.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * Authorize and describe one readable file. + * + * @param fileId the file + * @param context the caller + */ +public record PrepareDownloadQuery(FileId fileId, RequestContext context) implements Query { + + public PrepareDownloadQuery { + Objects.requireNonNull(fileId, "fileId"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadUseCase.java new file mode 100644 index 00000000..2bdcd934 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/PrepareDownloadUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.download.DownloadDescriptor; +import dev.caskeleton.application.usecase.QueryUseCase; + +/** Authorizes a download and describes the readable representation it will serve. */ +public interface PrepareDownloadUseCase + extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReconcileOrphansUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReconcileOrphansUseCase.java new file mode 100644 index 00000000..a2db1f8b --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReconcileOrphansUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.admin.OrphanReconcileReport; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Removes, or with a dry run only lists, the orphaned objects an operator names. */ +public interface ReconcileOrphansUseCase + extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileCommand.java new file mode 100644 index 00000000..df18f161 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileCommand.java @@ -0,0 +1,20 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.util.Objects; + +/** + * Re-verify one quarantined file. + * + * @param fileId the quarantined file + * @param context the operator + */ +public record ReverifyFileCommand(FileId fileId, RequestContext context) implements Command { + + public ReverifyFileCommand { + Objects.requireNonNull(fileId, "fileId"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileUseCase.java new file mode 100644 index 00000000..ef530691 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/ReverifyFileUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Sends a quarantined file back to verification. */ +public interface ReverifyFileUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentQuery.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentQuery.java new file mode 100644 index 00000000..efe952a8 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentQuery.java @@ -0,0 +1,24 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.api.ByteRange; +import dev.caskeleton.application.fileserver.download.DownloadDescriptor; +import dev.caskeleton.application.query.Query; +import java.nio.channels.WritableByteChannel; +import java.util.Objects; + +/** + * Transfer a range of a prepared download straight into a sink. + * + * @param descriptor what an authorized prepare returned + * @param byteRange the bytes to send + * @param sink where the storage sends them + */ +public record TransferDownloadContentQuery( + DownloadDescriptor descriptor, ByteRange byteRange, WritableByteChannel sink) implements Query { + + public TransferDownloadContentQuery { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(byteRange, "byteRange"); + Objects.requireNonNull(sink, "sink"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentUseCase.java new file mode 100644 index 00000000..f5274bf9 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/TransferDownloadContentUseCase.java @@ -0,0 +1,8 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.download.ZeroCopyTransferResult; +import dev.caskeleton.application.usecase.QueryUseCase; + +/** Hands a prepared download to the storage for a kernel-level transfer, when it can. */ +public interface TransferDownloadContentUseCase + extends QueryUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileCommand.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileCommand.java new file mode 100644 index 00000000..95bd6238 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileCommand.java @@ -0,0 +1,33 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.command.Command; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; +import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest; +import java.nio.channels.ReadableByteChannel; +import java.util.Objects; + +/** + * Upload one whole file in a single request. + * + * @param request what the client asked for + * @param content the whole body; the caller owns and closes it + * @param contentLength the declared length, or a negative value when unknown + * @param finalizeRequest the client's finalization assertions + * @param context the caller + */ +public record UploadFileCommand( + CreateUploadRequest request, + ReadableByteChannel content, + long contentLength, + FinalizeUploadRequest finalizeRequest, + RequestContext context) + implements Command { + + public UploadFileCommand { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(content, "content"); + Objects.requireNonNull(finalizeRequest, "finalizeRequest"); + Objects.requireNonNull(context, "context"); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileUseCase.java new file mode 100644 index 00000000..d4e11854 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/port/in/UploadFileUseCase.java @@ -0,0 +1,7 @@ +package dev.caskeleton.application.fileserver.port.in; + +import dev.caskeleton.application.fileserver.upload.FileView; +import dev.caskeleton.application.usecase.CommandUseCase; + +/** Stores a whole file in one request: create, append and finalize as one operation. */ +public interface UploadFileUseCase extends CommandUseCase {} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java new file mode 100644 index 00000000..c9635a9e --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/AppendUploadApplicationUseCase.java @@ -0,0 +1,170 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.content.AppendResult; +import dev.caskeleton.application.fileserver.api.content.UploadHandle; +import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.metadata.WriterLease; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.concurrency.LeaseFence; +import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; +import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; +import dev.caskeleton.application.fileserver.observability.SizeBucket; +import dev.caskeleton.application.fileserver.port.in.AppendUploadCommand; +import dev.caskeleton.application.fileserver.port.in.AppendUploadUseCase; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; +import dev.caskeleton.application.fileserver.quota.TransferPermit; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; + +/** + * Appends one chunk to an open upload under a writer lease. + * + *

    Three separate boundaries, not one: the byte transfer between them must not run inside a + * transaction, so the lease, the offset commit, and the release each stand alone. + */ +@RequiresPermission("file:upload") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class AppendUploadApplicationUseCase implements AppendUploadUseCase { + + /** One bounded value, because the platform has exactly one storage provider. */ + private static final String STORAGE_TYPE = "local"; + + private final FileMetadataPort metadataStore; + private final UploadSessionPort sessionStore; + private final WriterLeaseCoordinator leaseCoordinator; + private final UploadStoragePort storageGateway; + private final TransferAdmissionController admissionController; + private final FileAccessPolicyPort accessPolicy; + private final UploadPolicy uploadPolicy; + private final FileserverMetricsPort metrics; + private final TransactionPort transactions; + private final Clock clock; + + public AppendUploadApplicationUseCase( + UploadStores stores, + UploadPolicies policies, + WriterLeaseCoordinator leaseCoordinator, + UploadStoragePort storageGateway, + TransferAdmissionController admissionController, + FileserverMetricsPort metrics, + TransactionPort transactions, + Clock clock) { + this.metadataStore = stores.metadata(); + this.sessionStore = stores.sessions(); + this.leaseCoordinator = Objects.requireNonNull(leaseCoordinator, "leaseCoordinator"); + this.storageGateway = Objects.requireNonNull(storageGateway, "storageGateway"); + this.admissionController = Objects.requireNonNull(admissionController, "admissionController"); + this.accessPolicy = policies.access(); + this.uploadPolicy = policies.upload(); + this.metrics = Objects.requireNonNull(metrics, "metrics"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public AppendUploadResult handle(AppendUploadCommand command) { + UploadId uploadId = command.uploadId(); + long expectedOffset = command.expectedOffset(); + RequestContext context = command.context(); + UploadSession session = UploadSessions.requireActive(sessionStore, uploadId, clock.instant()); + FileRecord record = FileRecords.require(metadataStore, session.fileId()); + accessPolicy.authorize( + FileOperation.APPEND, context.subject(), Optional.of(record.toDescriptor())); + + try (TransferPermit permit = + admissionController.acquireUpload( + UploadSessions.admissionScope(context), Math.max(command.contentLength(), 0))) { + WriterLease lease = leaseCoordinator.acquire(uploadId, context.instanceId()); + // The fence is what carries the lease through the transfer. It renews on its own heartbeat + // and refuses the next write the moment renewal is denied, so a transfer that outlives its + // lease stops at a buffer boundary instead of discovering the takeover at commit time — by + // which point its bytes would already be interleaved with the new writer's. + LeaseFence fence = leaseCoordinator.fence(lease); + try { + UploadHandle handle = + storageGateway.reattachStaging( + uploadId, + record.namespace(), + UploadSessions.effectiveMaximum(uploadPolicy, record.expectedSize())); + requireOffsetsAgree(session, handle, expectedOffset); + + Instant startedAt = clock.instant(); + // The chunk checksum is checked by the store before it returns, so a mismatch never reaches + // the offset commit below. + AppendResult appended = + storageGateway.append( + handle, + expectedOffset, + command.content(), + command.contentLength(), + command.expectedChunkSha256(), + fence); + // The coordinator's own boundary joins this one; it is named here so the one write this + // operation commits after the transfer is visibly a write. + UploadSession committed = + transactions.inWrite( + () -> + leaseCoordinator.commitOffset( + fence.current(), expectedOffset, appended.committedOffset())); + // Recorded here rather than at the transport, because this is where the mode, the + // durable result and the byte count are all facts rather than inferences. + metrics.recordUpload( + session.mode(), + STORAGE_TYPE, + "committed", + SizeBucket.of(appended.appendedBytes()), + Duration.between(startedAt, clock.instant()), + appended.appendedBytes()); + return new AppendUploadResult( + committed.committedOffset(), appended.appendedBytes(), appended.sha256()); + } catch (UploadOffsetMismatchException mismatch) { + metrics.recordOffsetMismatch(session.mode(), "client"); + throw mismatch; + } finally { + leaseCoordinator.release(fence.current()); + } + } + } + + /** + * Cross-checks the resumable offset against the bytes actually on disk. + * + *

    A metadata offset that disagrees with the physical length means an earlier append is + * unaccounted for. Appending anyway would corrupt the object, so this is a hard conflict. + */ + private void requireOffsetsAgree( + UploadSession session, UploadHandle handle, long expectedOffset) { + long physicalLength = storageGateway.stagingLength(handle); + if (session.committedOffset() != physicalLength) { + throw UploadOffsetMismatchException.of( + session.uploadId(), session.committedOffset(), physicalLength); + } + if (expectedOffset != session.committedOffset()) { + throw UploadOffsetMismatchException.of( + session.uploadId(), expectedOffset, session.committedOffset()); + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CancelUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CancelUploadApplicationUseCase.java new file mode 100644 index 00000000..39739952 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CancelUploadApplicationUseCase.java @@ -0,0 +1,73 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.cleanup.FileRetirement; +import dev.caskeleton.application.fileserver.port.in.CancelUploadCommand; +import dev.caskeleton.application.fileserver.port.in.CancelUploadUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.Objects; +import java.util.Optional; + +/** + * Cancels an upload: the record stops being reachable and its bytes are queued for removal. + * + *

    {@code file:upload}, not {@code file:delete}: a caller that may start an upload may abandon + * its own, the same way {@code operation:submit} and {@code operation:cancel} go to one role. + */ +@RequiresPermission("file:upload") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class CancelUploadApplicationUseCase implements CancelUploadUseCase { + + private final FileMetadataPort metadataStore; + private final UploadSessionPort sessionStore; + private final FileAccessPolicyPort accessPolicy; + private final FileRetirement retirement; + private final TransactionPort transactions; + + public CancelUploadApplicationUseCase( + UploadStores stores, FileAccessPolicyPort accessPolicy, TransactionPort transactions) { + this.metadataStore = stores.metadata(); + this.sessionStore = stores.sessions(); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.retirement = new FileRetirement(stores.metadata(), stores.cleanupQueue()); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + @Override + public Void handle(CancelUploadCommand command) { + UploadSession session = UploadSessions.require(sessionStore, command.uploadId()); + FileRecord record = FileRecords.require(metadataStore, session.fileId()); + accessPolicy.authorize( + FileOperation.DELETE, command.context().subject(), Optional.of(record.toDescriptor())); + + transactions.inWrite( + () -> { + // Logical first: the record must stop being reachable before any physical work is + // scheduled. The staged bytes and, for an upload that was already published, the + // published object are queued in the same commit, so no cancel can leave a file + // unreachable with nothing queued to reclaim it. + retirement.retire(record, Optional.of(session.uploadId())); + // Terminal in the same transaction that queues the cleanup. Queuing alone left the + // session ACTIVE, so a writer could still take a lease on the very bytes the cleanup was + // about to delete and the two raced for the same object. + sessionStore.terminate(session.uploadId()); + }); + return null; + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java new file mode 100644 index 00000000..1e85864e --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/CreateUploadApplicationUseCase.java @@ -0,0 +1,204 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.FileState; +import dev.caskeleton.application.fileserver.api.StorageNamespace; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; +import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; +import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.api.security.SanitizedFilename; +import dev.caskeleton.application.fileserver.port.in.CreateUploadCommand; +import dev.caskeleton.application.fileserver.port.in.CreateUploadUseCase; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; +import dev.caskeleton.application.fileserver.quota.TransferPermit; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalLong; + +/** + * Opens an upload: quota, file record and session in one boundary, then staging. + * + *

    Two authorities, both required. {@code file:upload} is the role check, enforced on the proxy + * before this runs; {@link FileAccessPolicyPort} is the tier and owner/tenant check, run first + * inside so a denial has no side effect. + */ +@RequiresPermission("file:upload") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class CreateUploadApplicationUseCase implements CreateUploadUseCase { + + private final FileMetadataPort metadataStore; + private final UploadSessionPort sessionStore; + private final UploadStoragePort storageGateway; + private final FileQuotaPort quotaService; + private final TransferAdmissionController admissionController; + private final FileAccessPolicyPort accessPolicy; + private final OriginalFilenamePolicy filenamePolicy; + private final UploadIdentifierPort identifierFactory; + private final UploadPolicy uploadPolicy; + private final TransactionPort transactions; + private final Clock clock; + + public CreateUploadApplicationUseCase( + UploadStores stores, + UploadPolicies policies, + UploadStoragePort storageGateway, + FileQuotaPort quotaService, + TransferAdmissionController admissionController, + UploadIdentifierPort identifierFactory, + TransactionPort transactions, + Clock clock) { + this.metadataStore = stores.metadata(); + this.sessionStore = stores.sessions(); + this.storageGateway = Objects.requireNonNull(storageGateway, "storageGateway"); + this.quotaService = Objects.requireNonNull(quotaService, "quotaService"); + this.admissionController = Objects.requireNonNull(admissionController, "admissionController"); + this.accessPolicy = policies.access(); + this.filenamePolicy = policies.filenames(); + this.identifierFactory = Objects.requireNonNull(identifierFactory, "identifierFactory"); + this.uploadPolicy = policies.upload(); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public UploadSessionView handle(CreateUploadCommand command) { + CreateUploadRequest request = command.request(); + RequestContext context = command.context(); + accessPolicy.authorize(FileOperation.CREATE, context.subject(), Optional.empty()); + requireLengthWithinPolicy(request.expectedLength()); + + SanitizedFilename displayName = filenamePolicy.sanitize(request.originalFilename()); + StorageNamespace namespace = uploadPolicy.defaultNamespace(); + Instant expiresAt = uploadPolicy.sessionExpiresAt(clock.instant()); + QuotaScope scope = QuotaScope.ofNamespace(namespace.value()); + long reservationBytes = request.expectedLength().orElse(uploadPolicy.initialReservationBytes()); + + try (TransferPermit permit = + admissionController.acquireUpload( + UploadSessions.admissionScope(context), reservationBytes)) { + FileId fileId = identifierFactory.newFileId(); + UploadId uploadId = identifierFactory.newUploadId(); + + // One unit: a reservation that outlived a failed insert would hold capacity for a file that + // never existed, and a session without its record is unresolvable by any later step. + CreatedUpload created = + transactions.inWrite( + () -> { + QuotaReservation reservation = + quotaService.reserve(scope, reservationBytes, uploadPolicy.reservationTtl()); + FileRecord record = + metadataStore.insert( + new FileRecordDraft( + fileId, + namespace, + displayName.value(), + request.claimedMediaType(), + request.expectedLength(), + context.subject().asOwner())); + UploadSession session = + sessionStore.create( + new UploadSessionDraft( + uploadId, fileId, request.mode(), request.expectedLength(), expiresAt)); + return new CreatedUpload(reservation, record, session); + }); + + try { + storageGateway.createStaging( + uploadId, + namespace, + UploadSessions.effectiveMaximum(uploadPolicy, request.expectedLength())); + } catch (RuntimeException exception) { + // Staging sits outside the boundary above because it has to — it is a filesystem call — so + // it is the one failure here that still compensates by hand instead of rolling back. + try { + transactions.inNew( + () -> { + failRecord(created.record(), "UPLOAD_CREATE_FAILED"); + quotaService.release(created.reservation()); + }); + } catch (RuntimeException compensationFailure) { + exception.addSuppressed(compensationFailure); + } + throw exception; + } + + transactions.inWrite( + () -> { + metadataStore.transition( + created.record().fileId(), + created.record().version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()); + }); + return UploadSessions.toView(created.session()); + } + } + + /** The three records one create produces, so a single boundary can return them together. */ + private record CreatedUpload( + QuotaReservation reservation, FileRecord record, UploadSession session) {} + + private void requireLengthWithinPolicy(OptionalLong expectedLength) { + if (expectedLength.isPresent() && expectedLength.getAsLong() > uploadPolicy.maximumFileSize()) { + throw new FileserverException( + "declared upload length exceeds the configured maximum file size", + FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false)); + } + } + + /** + * Moves a record to FAILED using only edges the state machine allows. + * + *

    The design requires a failed create to end in FAILED, but the transition table has no direct + * {@code CREATED -> FAILED} edge. The record therefore takes the one path the table permits, + * through UPLOADING, which is also honest: the upload had been admitted before it failed. + */ + private void failRecord(FileRecord record, String reasonCode) { + FileRecord current = record; + if (current.state() == FileState.CREATED) { + current = + metadataStore.transition( + current.fileId(), + current.version(), + FileState.CREATED, + FileState.UPLOADING, + FileRecordMutation.none()); + } + metadataStore.transition( + current.fileId(), + current.version(), + current.state(), + FileState.FAILED, + FileRecordMutation.failure(reasonCode)); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadService.java deleted file mode 100644 index b549b0f6..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadService.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import dev.caskeleton.application.fileserver.api.UploadId; -import dev.caskeleton.application.fileserver.api.error.AmbiguousCompletionException; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import java.nio.channels.ReadableByteChannel; - -/** - * Composes create, append, and finalize into the one-request upload. - * - *

    The cancel-on-failure rule is the substance here. A transfer that fails outright leaves an - * orphan staging object and a reserved quota slice, so it is cancelled; an ambiguous - * completion is deliberately left alone, because its content may already be published and only - * reconciliation may decide its fate. - */ -public final class DefaultSingleShotUploadService implements SingleShotUploadService { - - private final UploadApplicationService uploadService; - private final FinalizeUploadService finalizeService; - - public DefaultSingleShotUploadService( - UploadApplicationService uploadService, FinalizeUploadService finalizeService) { - this.uploadService = uploadService; - this.finalizeService = finalizeService; - } - - @Override - public FileView upload( - CreateUploadRequest request, - ReadableByteChannel content, - long contentLength, - FinalizeUploadRequest finalizeRequest, - RequestContext context) { - UploadSessionView created = uploadService.create(request, context); - try { - uploadService.append(created.uploadId(), 0, content, contentLength, context); - return finalizeService.finalizeUpload(created.uploadId(), finalizeRequest, context); - } catch (RuntimeException failure) { - if (!(failure instanceof AmbiguousCompletionException)) { - cancelQuietly(created.uploadId(), context, failure); - } - throw failure; - } - } - - /** - * Best-effort cancel of the upload resource. - * - *

    A cancel that itself fails must not replace the original failure: the caller would then be - * told about a cleanup problem instead of the reason their upload did not work. It is attached as - * a suppressed cause so nothing is silently lost either. - */ - private void cancelQuietly(UploadId uploadId, RequestContext context, RuntimeException failure) { - try { - uploadService.cancel(uploadId, context); - } catch (RuntimeException cleanupFailure) { - failure.addSuppressed(cleanupFailure); - } - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java deleted file mode 100644 index 4caafe2e..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java +++ /dev/null @@ -1,387 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.FileState; -import dev.caskeleton.application.fileserver.api.StorageNamespace; -import dev.caskeleton.application.fileserver.api.UploadId; -import dev.caskeleton.application.fileserver.api.content.AppendResult; -import dev.caskeleton.application.fileserver.api.content.UploadHandle; -import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; -import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; -import dev.caskeleton.application.fileserver.api.error.FileserverException; -import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException; -import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; -import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; -import dev.caskeleton.application.fileserver.api.metadata.FileRecord; -import dev.caskeleton.application.fileserver.api.metadata.FileRecordDraft; -import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; -import dev.caskeleton.application.fileserver.api.metadata.QuotaReservation; -import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; -import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.metadata.UploadSessionDraft; -import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; -import dev.caskeleton.application.fileserver.api.metadata.WriterLease; -import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; -import dev.caskeleton.application.fileserver.api.security.FileOperation; -import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.api.security.SanitizedFilename; -import dev.caskeleton.application.fileserver.cleanup.FileRetirement; -import dev.caskeleton.application.fileserver.concurrency.LeaseFence; -import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; -import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; -import dev.caskeleton.application.fileserver.observability.SizeBucket; -import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; -import dev.caskeleton.application.fileserver.quota.TransferPermit; -import dev.caskeleton.application.transaction.TransactionPort; -import java.nio.channels.ReadableByteChannel; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.OptionalLong; - -/** - * Orchestrates create, append, status, and cancel. - * - *

    Two ordering rules carry most of the safety here. Authorization runs before admission, quota, - * and any storage call, so a denial has no side effect. On append, the metadata offset and the - * physical staging length must agree before a byte is written; when they disagree the upload goes - * to reconciliation rather than being silently repaired. - * - *

    This service owns its transaction boundaries. They are deliberately narrow: a boundary covers - * a contiguous run of metadata writes and stops before every storage call, because a filesystem - * operation inside a database transaction would hold a connection for the length of a byte - * transfer. What that costs is atomicity across the storage/metadata seam, which no database - * boundary could have provided anyway — that seam is what the reconciler exists for. - */ -public final class DefaultUploadApplicationService implements UploadApplicationService { - - private final FileMetadataPort metadataStore; - private final UploadSessionPort sessionStore; - private final WriterLeaseCoordinator leaseCoordinator; - private final UploadStoragePort storageGateway; - private final FileQuotaPort quotaService; - private final TransferAdmissionController admissionController; - private final FileAccessPolicyPort accessPolicy; - private final OriginalFilenamePolicy filenamePolicy; - private final FileRetirement retirement; - private final UploadIdentifierPort identifierFactory; - private final UploadPolicy uploadPolicy; - private final FileserverMetricsPort metrics; - private final TransactionPort transactions; - private final Clock clock; - - public DefaultUploadApplicationService( - UploadStores stores, - UploadPolicies policies, - WriterLeaseCoordinator leaseCoordinator, - UploadStoragePort storageGateway, - FileQuotaPort quotaService, - TransferAdmissionController admissionController, - UploadIdentifierPort identifierFactory, - FileserverMetricsPort metrics, - TransactionPort transactions, - Clock clock) { - this.transactions = transactions; - this.metadataStore = stores.metadata(); - this.sessionStore = stores.sessions(); - this.leaseCoordinator = leaseCoordinator; - this.storageGateway = storageGateway; - this.quotaService = quotaService; - this.admissionController = admissionController; - this.accessPolicy = policies.access(); - this.filenamePolicy = policies.filenames(); - this.retirement = new FileRetirement(stores.metadata(), stores.cleanupQueue()); - this.identifierFactory = identifierFactory; - this.uploadPolicy = policies.upload(); - this.metrics = metrics; - this.clock = clock; - } - - @Override - public UploadSessionView create(CreateUploadRequest request, RequestContext context) { - accessPolicy.authorize(FileOperation.CREATE, context.subject(), Optional.empty()); - requireLengthWithinPolicy(request.expectedLength()); - - SanitizedFilename displayName = filenamePolicy.sanitize(request.originalFilename()); - StorageNamespace namespace = uploadPolicy.defaultNamespace(); - Instant expiresAt = uploadPolicy.sessionExpiresAt(clock.instant()); - QuotaScope scope = QuotaScope.ofNamespace(namespace.value()); - long reservationBytes = request.expectedLength().orElse(uploadPolicy.initialReservationBytes()); - - try (TransferPermit permit = - admissionController.acquireUpload(admissionScope(context), reservationBytes)) { - FileId fileId = identifierFactory.newFileId(); - UploadId uploadId = identifierFactory.newUploadId(); - - // One unit: a reservation that outlived a failed insert would hold capacity for a file that - // never existed, and a session without its record is unresolvable by any later step. - CreatedUpload created = - transactions.inWrite( - () -> { - QuotaReservation reservation = - quotaService.reserve(scope, reservationBytes, uploadPolicy.reservationTtl()); - FileRecord record = - metadataStore.insert( - new FileRecordDraft( - fileId, - namespace, - displayName.value(), - request.claimedMediaType(), - request.expectedLength(), - context.subject().asOwner())); - UploadSession session = - sessionStore.create( - new UploadSessionDraft( - uploadId, fileId, request.mode(), request.expectedLength(), expiresAt)); - return new CreatedUpload(reservation, record, session); - }); - - try { - storageGateway.createStaging( - uploadId, namespace, effectiveMaximum(request.expectedLength())); - } catch (RuntimeException exception) { - // Staging sits outside the boundary above because it has to — it is a filesystem call — so - // it is the one failure here that still compensates by hand instead of rolling back. - try { - transactions.inNew( - () -> { - failRecord(created.record(), "UPLOAD_CREATE_FAILED"); - quotaService.release(created.reservation()); - }); - } catch (RuntimeException compensationFailure) { - exception.addSuppressed(compensationFailure); - } - throw exception; - } - - transactions.inWrite( - () -> { - metadataStore.transition( - created.record().fileId(), - created.record().version(), - FileState.CREATED, - FileState.UPLOADING, - FileRecordMutation.none()); - }); - return toView(created.session()); - } - } - - /** The three records one create produces, so a single boundary can return them together. */ - private record CreatedUpload( - QuotaReservation reservation, FileRecord record, UploadSession session) {} - - @Override - public AppendUploadResult append( - UploadId uploadId, - long expectedOffset, - ReadableByteChannel content, - long contentLength, - Optional expectedChunkSha256, - RequestContext context) { - UploadSession session = requireActiveSession(uploadId); - FileRecord record = requireRecord(session.fileId()); - accessPolicy.authorize( - FileOperation.APPEND, context.subject(), Optional.of(record.toDescriptor())); - - try (TransferPermit permit = - admissionController.acquireUpload(admissionScope(context), Math.max(contentLength, 0))) { - // Three separate boundaries, not one: the byte transfer between them must not run inside a - // transaction, so the lease, the offset commit, and the release each stand alone. - WriterLease lease = leaseCoordinator.acquire(uploadId, context.instanceId()); - // The fence is what carries the lease through the transfer. It renews on its own heartbeat - // and refuses the next write the moment renewal is denied, so a transfer that outlives its - // lease stops at a buffer boundary instead of discovering the takeover at commit time — by - // which point its bytes would already be interleaved with the new writer's. - LeaseFence fence = leaseCoordinator.fence(lease); - try { - UploadHandle handle = - storageGateway.reattachStaging( - uploadId, record.namespace(), effectiveMaximum(record.expectedSize())); - requireOffsetsAgree(session, handle, expectedOffset); - - Instant startedAt = clock.instant(); - // The chunk checksum is checked by the store before it returns, so a mismatch never reaches - // the offset commit below. - AppendResult appended = - storageGateway.append( - handle, expectedOffset, content, contentLength, expectedChunkSha256, fence); - UploadSession committed = - leaseCoordinator.commitOffset( - fence.current(), expectedOffset, appended.committedOffset()); - // Recorded here rather than at the transport, because this is where the mode, the - // durable result and the byte count are all facts rather than inferences. - metrics.recordUpload( - session.mode(), - STORAGE_TYPE, - "committed", - SizeBucket.of(appended.appendedBytes()), - Duration.between(startedAt, clock.instant()), - appended.appendedBytes()); - return new AppendUploadResult( - committed.committedOffset(), appended.appendedBytes(), appended.sha256()); - } catch (UploadOffsetMismatchException mismatch) { - metrics.recordOffsetMismatch(session.mode(), "client"); - throw mismatch; - } finally { - leaseCoordinator.release(fence.current()); - } - } - } - - @Override - public UploadSessionView status(UploadId uploadId, RequestContext context) { - // An ended upload answers gone, not with an offset a client would try to resume from. - UploadSession session = requireActiveSession(uploadId); - FileRecord record = requireRecord(session.fileId()); - accessPolicy.authorize( - FileOperation.READ_METADATA, context.subject(), Optional.of(record.toDescriptor())); - return toView(session); - } - - @Override - public void cancel(UploadId uploadId, RequestContext context) { - UploadSession session = requireSession(uploadId); - FileRecord record = requireRecord(session.fileId()); - accessPolicy.authorize( - FileOperation.DELETE, context.subject(), Optional.of(record.toDescriptor())); - - transactions.inWrite( - () -> { - // Logical first: the record must stop being reachable before any physical work is - // scheduled. The staged bytes and, for an upload that was already published, the - // published object are queued in the same commit, so no cancel can leave a file - // unreachable with nothing queued to reclaim it. - retirement.retire(record, Optional.of(session.uploadId())); - // Terminal in the same transaction that queues the cleanup. Queuing alone left the - // session ACTIVE, so a writer could still take a lease on the very bytes the cleanup was - // about to delete and the two raced for the same object. - sessionStore.terminate(session.uploadId()); - }); - } - - /** - * Transfer concurrency is counted per caller. - * - *

    Counting it per namespace put every caller of a deployment — which uploads into one default - * namespace — behind the same handful of permits, so one busy client refused everyone else. - */ - private static QuotaScope admissionScope(RequestContext context) { - return QuotaScope.ofPrincipal(context.subject().principalId()); - } - - /** - * Cross-checks the resumable offset against the bytes actually on disk. - * - *

    A metadata offset that disagrees with the physical length means an earlier append is - * unaccounted for. Appending anyway would corrupt the object, so this is a hard conflict. - */ - /** One bounded value, because the platform has exactly one storage provider. */ - private static final String STORAGE_TYPE = "local"; - - private void requireOffsetsAgree( - UploadSession session, UploadHandle handle, long expectedOffset) { - long physicalLength = storageGateway.stagingLength(handle); - if (session.committedOffset() != physicalLength) { - throw UploadOffsetMismatchException.of( - session.uploadId(), session.committedOffset(), physicalLength); - } - if (expectedOffset != session.committedOffset()) { - throw UploadOffsetMismatchException.of( - session.uploadId(), expectedOffset, session.committedOffset()); - } - } - - private void requireLengthWithinPolicy(OptionalLong expectedLength) { - if (expectedLength.isPresent() && expectedLength.getAsLong() > uploadPolicy.maximumFileSize()) { - throw new FileserverException( - "declared upload length exceeds the configured maximum file size", - FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false)); - } - } - - private long effectiveMaximum(OptionalLong expectedLength) { - return expectedLength.isPresent() - ? Math.min(uploadPolicy.maximumFileSize(), Math.max(expectedLength.getAsLong(), 1)) - : uploadPolicy.maximumFileSize(); - } - - private UploadSession requireSession(UploadId uploadId) { - return sessionStore - .find(uploadId) - .orElseThrow( - () -> - new FileNotFoundException( - "upload resource does not exist", - FileserverFailureContext.forUpload( - FileserverErrorCode.FILE_NOT_FOUND, uploadId, false, false, false))); - } - - private UploadSession requireActiveSession(UploadId uploadId) { - UploadSession session = requireSession(uploadId); - if (session.terminal()) { - // Cancelled, rejected or swept. Refusing it as a lease conflict told the client to retry an - // upload that can never accept another byte. - throw new FileserverException( - "upload resource is no longer open", - FileserverFailureContext.forUpload( - FileserverErrorCode.UPLOAD_EXPIRED, uploadId, false, false, false)); - } - if (session.isExpiredAt(clock.instant())) { - throw new FileserverException( - "upload resource has expired", - FileserverFailureContext.forUpload( - FileserverErrorCode.UPLOAD_EXPIRED, uploadId, false, false, false)); - } - return session; - } - - private FileRecord requireRecord(FileId fileId) { - return metadataStore - .find(fileId) - .orElseThrow( - () -> - new FileNotFoundException( - "file record does not exist", - FileserverFailureContext.forFile( - FileserverErrorCode.FILE_NOT_FOUND, fileId, false))); - } - - /** - * Moves a record to FAILED using only edges the state machine allows. - * - *

    The design requires a failed create to end in FAILED, but the transition table has no direct - * {@code CREATED -> FAILED} edge. The record therefore takes the one path the table permits, - * through UPLOADING, which is also honest: the upload had been admitted before it failed. - */ - private void failRecord(FileRecord record, String reasonCode) { - FileRecord current = record; - if (current.state() == FileState.CREATED) { - current = - metadataStore.transition( - current.fileId(), - current.version(), - FileState.CREATED, - FileState.UPLOADING, - FileRecordMutation.none()); - } - metadataStore.transition( - current.fileId(), - current.version(), - current.state(), - FileState.FAILED, - FileRecordMutation.failure(reasonCode)); - } - - private static UploadSessionView toView(UploadSession session) { - return new UploadSessionView( - session.uploadId(), - session.fileId(), - session.committedOffset(), - session.expectedLength(), - session.expiresAt()); - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java similarity index 93% rename from src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java rename to src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java index e958085e..64520ca5 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCase.java @@ -1,5 +1,8 @@ package dev.caskeleton.application.fileserver.upload; +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; import dev.caskeleton.application.fileserver.api.ContentKey; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.UploadId; @@ -27,7 +30,11 @@ import dev.caskeleton.application.fileserver.api.security.VerificationVerdict; import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; +import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand; +import dev.caskeleton.application.fileserver.port.in.FinalizeUploadUseCase; import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Instant; @@ -44,7 +51,15 @@ import java.util.OptionalLong; * the physical publish, the caller gets an ambiguous completion and the file goes to the recovery * queue — never a READY answer the store cannot back. */ -public final class DefaultFinalizeUploadService implements FinalizeUploadService { +@RequiresPermission("file:upload") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, + externalOutboundAllowed = true) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class FinalizeUploadApplicationUseCase implements FinalizeUploadUseCase { private final FileMetadataPort metadataStore; private final UploadSessionPort sessionStore; @@ -58,7 +73,7 @@ public final class DefaultFinalizeUploadService implements FinalizeUploadService private final TransactionPort transactions; private final Clock clock; - public DefaultFinalizeUploadService( + public FinalizeUploadApplicationUseCase( FileMetadataPort metadataStore, UploadSessionPort sessionStore, UploadContentPort contentGateway, @@ -84,8 +99,8 @@ public final class DefaultFinalizeUploadService implements FinalizeUploadService } @Override - public FileView finalizeUpload( - UploadId uploadId, FinalizeUploadRequest request, RequestContext context) { + public FileView handle(FinalizeUploadCommand command) { + UploadId uploadId = command.uploadId(); UploadSession session = sessionStore .find(uploadId) @@ -95,11 +110,10 @@ public final class DefaultFinalizeUploadService implements FinalizeUploadService "upload resource does not exist", FileserverFailureContext.forUpload( FileserverErrorCode.FILE_NOT_FOUND, uploadId, false, false, false))); - return finalizeUpload(session, request, context); + return finalizeSession(session, command.request(), command.context()); } - @Override - public FileView finalizeUpload( + private FileView finalizeSession( UploadSession session, FinalizeUploadRequest request, RequestContext context) { FileRecord record = requireRecord(session); // Before any digest, verification or publish: a denial must have no side effect. diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadService.java deleted file mode 100644 index 6fae5a56..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadService.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import dev.caskeleton.application.fileserver.api.UploadId; -import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.security.RequestContext; - -/** - * Completes an upload and decides whether it may become publicly readable. - * - *

    READY is only ever reached after the physical object is published and re-verified, so a READY - * record always has readable content whose size and digest match. - */ -public interface FinalizeUploadService { - - FileView finalizeUpload( - UploadSession session, FinalizeUploadRequest request, RequestContext context); - - /** - * Transport-facing entry point that resolves the session itself. - * - *

    A transport adapter only ever holds the opaque {@link UploadId}; letting it fetch an {@code - * UploadSession} would put a metadata port type in a controller signature. - */ - FileView finalizeUpload(UploadId uploadId, FinalizeUploadRequest request, RequestContext context); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/GetUploadStatusApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/GetUploadStatusApplicationUseCase.java new file mode 100644 index 00000000..977256f1 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/GetUploadStatusApplicationUseCase.java @@ -0,0 +1,72 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; +import dev.caskeleton.application.fileserver.api.metadata.FileRecord; +import dev.caskeleton.application.fileserver.api.metadata.FileRecords; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.GetUploadStatusQuery; +import dev.caskeleton.application.fileserver.port.in.GetUploadStatusUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.util.Objects; +import java.util.Optional; + +/** + * Reports where an open upload stands. + * + *

    {@code file:read}, matching the metadata-read tier {@link FileAccessPolicyPort} checks inside + * along with ownership: resuming an upload means asking where one's own upload stands. + */ +@RequiresPermission("file:read") +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.READ_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class GetUploadStatusApplicationUseCase implements GetUploadStatusUseCase { + + private final FileMetadataPort metadataStore; + private final UploadSessionPort sessionStore; + private final FileAccessPolicyPort accessPolicy; + private final TransactionPort transactions; + private final Clock clock; + + public GetUploadStatusApplicationUseCase( + UploadStores stores, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions, + Clock clock) { + this.metadataStore = stores.metadata(); + this.sessionStore = stores.sessions(); + this.accessPolicy = Objects.requireNonNull(accessPolicy, "accessPolicy"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public UploadSessionView handle(GetUploadStatusQuery query) { + // The session and its record read together, so the owner the policy judges is the owner of the + // session being reported. + return transactions.inRead( + () -> { + // An ended upload answers gone, not with an offset a client would try to resume from. + UploadSession session = + UploadSessions.requireActive(sessionStore, query.uploadId(), clock.instant()); + FileRecord record = FileRecords.require(metadataStore, session.fileId()); + accessPolicy.authorize( + FileOperation.READ_METADATA, + query.context().subject(), + Optional.of(record.toDescriptor())); + return UploadSessions.toView(session); + }); + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/SingleShotUploadService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/SingleShotUploadService.java deleted file mode 100644 index 0fece367..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/SingleShotUploadService.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import java.nio.channels.ReadableByteChannel; - -/** - * One-request upload: create, stream, finalize. - * - *

    The sequence belongs here rather than in a transport because it decides lifecycle: which - * failures cancel the upload resource, and which leave it for reconciliation. A controller that - * assembled the same three calls itself would be making that decision per transport. - */ -public interface SingleShotUploadService { - - /** - * Streams {@code content} into a new file and finalizes it. - * - * @param contentLength declared length, or a negative value when the request is chunked and the - * length is only known at end of stream - */ - FileView upload( - CreateUploadRequest request, - ReadableByteChannel content, - long contentLength, - FinalizeUploadRequest finalizeRequest, - RequestContext context); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java deleted file mode 100644 index d4cdf99a..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import dev.caskeleton.application.fileserver.api.UploadId; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import java.nio.channels.ReadableByteChannel; -import java.util.Optional; - -/** - * The upload half of the public application surface. - * - *

    Every method authorizes first, before any quota reservation or storage mutation, so a denied - * request leaves no record, no reservation, and no staging object behind. - */ -public interface UploadApplicationService { - - UploadSessionView create(CreateUploadRequest request, RequestContext context); - - /** - * Appends one request's bytes. - * - * @param expectedChunkSha256 hex SHA-256 the client asserted for this request's bytes only, never - * the whole upload; a mismatch is rejected before the offset commits and leaves no bytes - * behind - */ - AppendUploadResult append( - UploadId uploadId, - long expectedOffset, - ReadableByteChannel content, - long contentLength, - Optional expectedChunkSha256, - RequestContext context); - - /** Appends without a client checksum. */ - default AppendUploadResult append( - UploadId uploadId, - long expectedOffset, - ReadableByteChannel content, - long contentLength, - RequestContext context) { - return append(uploadId, expectedOffset, content, contentLength, Optional.empty(), context); - } - - UploadSessionView status(UploadId uploadId, RequestContext context); - - void cancel(UploadId uploadId, RequestContext context); -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCase.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCase.java new file mode 100644 index 00000000..5ea379cc --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCase.java @@ -0,0 +1,99 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.AmbiguousCompletionException; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +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.UploadFileCommand; +import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import java.util.Objects; +import java.util.Optional; + +/** + * Composes create, append, and finalize into the one-request upload. + * + *

    The cancel-on-failure rule is the substance here. A transfer that fails outright leaves an + * orphan staging object and a reserved quota slice, so it is cancelled; an ambiguous + * completion is deliberately left alone, because its content may already be published and only + * reconciliation may decide its fate. + * + *

    {@code RepositoryAccess.NONE}: this use case touches no store itself. Each step it composes is + * a use case that declares, and opens, its own boundaries — one transaction around the three would + * hold a connection for the length of the byte transfer. The permission is still declared: the + * composed steps check it again, but the operation a caller asks for is this one. + */ +@RequiresPermission("file:upload") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.NOT_IDEMPOTENT, + repositoryAccess = RepositoryAccess.NONE) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class UploadFileApplicationUseCase implements UploadFileUseCase { + + private final CreateUploadUseCase create; + private final AppendUploadUseCase append; + private final FinalizeUploadUseCase finalizer; + private final CancelUploadUseCase cancel; + + public UploadFileApplicationUseCase( + CreateUploadUseCase create, + AppendUploadUseCase append, + FinalizeUploadUseCase finalizer, + CancelUploadUseCase cancel) { + this.create = Objects.requireNonNull(create, "create"); + this.append = Objects.requireNonNull(append, "append"); + this.finalizer = Objects.requireNonNull(finalizer, "finalizer"); + this.cancel = Objects.requireNonNull(cancel, "cancel"); + } + + @Override + public FileView handle(UploadFileCommand command) { + RequestContext context = command.context(); + UploadSessionView created = create.handle(new CreateUploadCommand(command.request(), context)); + try { + append.handle( + new AppendUploadCommand( + created.uploadId(), + 0, + command.content(), + command.contentLength(), + Optional.empty(), + context)); + return finalizer.handle( + new FinalizeUploadCommand(created.uploadId(), command.finalizeRequest(), context)); + } catch (RuntimeException failure) { + if (!(failure instanceof AmbiguousCompletionException)) { + cancelQuietly(created.uploadId(), context, failure); + } + throw failure; + } + } + + /** + * Best-effort cancel of the upload resource. + * + *

    A cancel that itself fails must not replace the original failure: the caller would then be + * told about a cleanup problem instead of the reason their upload did not work. It is attached as + * a suppressed cause so nothing is silently lost either. + */ + private void cancelQuietly(UploadId uploadId, RequestContext context, RuntimeException failure) { + try { + cancel.handle(new CancelUploadCommand(uploadId, context)); + } catch (RuntimeException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java new file mode 100644 index 00000000..cf7adf77 --- /dev/null +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadSessions.java @@ -0,0 +1,79 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.FileserverException; +import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.metadata.QuotaScope; +import dev.caskeleton.application.fileserver.api.metadata.UploadSession; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import java.time.Instant; +import java.util.OptionalLong; + +/** + * The session lookups and limits the upload use cases share. + * + *

    They were private methods of one upload service. Split into one use case per operation, each + * would otherwise carry its own copy of the refusal a client sees for a missing or ended upload. + */ +final class UploadSessions { + + private UploadSessions() {} + + static UploadSession require(UploadSessionPort sessions, UploadId uploadId) { + return sessions + .find(uploadId) + .orElseThrow( + () -> + new FileNotFoundException( + "upload resource does not exist", + FileserverFailureContext.forUpload( + FileserverErrorCode.FILE_NOT_FOUND, uploadId, false, false, false))); + } + + static UploadSession requireActive(UploadSessionPort sessions, UploadId uploadId, Instant now) { + UploadSession session = require(sessions, uploadId); + if (session.terminal()) { + // Cancelled, rejected or swept. Refusing it as a lease conflict told the client to retry an + // upload that can never accept another byte. + throw new FileserverException( + "upload resource is no longer open", + FileserverFailureContext.forUpload( + FileserverErrorCode.UPLOAD_EXPIRED, uploadId, false, false, false)); + } + if (session.isExpiredAt(now)) { + throw new FileserverException( + "upload resource has expired", + FileserverFailureContext.forUpload( + FileserverErrorCode.UPLOAD_EXPIRED, uploadId, false, false, false)); + } + return session; + } + + /** + * Transfer concurrency is counted per caller. + * + *

    Counting it per namespace put every caller of a deployment — which uploads into one default + * namespace — behind the same handful of permits, so one busy client refused everyone else. + */ + static QuotaScope admissionScope(RequestContext context) { + return QuotaScope.ofPrincipal(context.subject().principalId()); + } + + static long effectiveMaximum(UploadPolicy policy, OptionalLong expectedLength) { + return expectedLength.isPresent() + ? Math.min(policy.maximumFileSize(), Math.max(expectedLength.getAsLong(), 1)) + : policy.maximumFileSize(); + } + + static UploadSessionView toView(UploadSession session) { + return new UploadSessionView( + session.uploadId(), + session.fileId(), + session.committedOffset(), + session.expectedLength(), + session.expiresAt()); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java similarity index 71% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminServiceTest.java rename to src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java index cad252d7..f2e48fc3 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/admin/FileserverAdminUseCasesTest.java @@ -16,29 +16,29 @@ import dev.caskeleton.application.fileserver.api.security.FileOperation; import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; -import dev.caskeleton.application.fileserver.cleanup.DefaultCleanupService; -import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint; +import dev.caskeleton.application.fileserver.port.in.ForceDeleteCommand; +import dev.caskeleton.application.fileserver.port.in.GetRuntimeCapabilitiesQuery; +import dev.caskeleton.application.fileserver.port.in.GetStorageHealthQuery; +import dev.caskeleton.application.fileserver.port.in.OrphanReconcileCommand; +import dev.caskeleton.application.fileserver.port.in.ReverifyFileCommand; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeAdminPorts; -import dev.caskeleton.application.fileserver.testkit.FakeCleanupContentGateway; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; import dev.caskeleton.application.fileserver.testkit.InMemoryCleanupQueue; import dev.caskeleton.application.fileserver.testkit.InMemoryFileMetadataStore; import dev.caskeleton.application.fileserver.testkit.InMemoryUploadSessionStore; import dev.caskeleton.application.fileserver.testkit.ReadyFileFixture; -import dev.caskeleton.application.fileserver.testkit.RecordingQuotaReclaimGateway; import java.nio.charset.StandardCharsets; import java.time.Clock; -import java.time.Duration; import java.time.ZoneOffset; import java.util.List; import java.util.OptionalLong; import java.util.UUID; import org.junit.jupiter.api.Test; -class FileserverAdminServiceTest { +class FileserverAdminUseCasesTest { private static final String DIGEST = "1".repeat(64); private static final long SIZE = 10; @@ -51,33 +51,33 @@ class FileserverAdminServiceTest { private final FakeFileAccessPolicy accessPolicy = new FakeFileAccessPolicy(); private final Clock clock = Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC); - private final FileserverAdminService admin = - new DefaultFileserverAdminService( - adminPorts, - adminPorts, - metadata, - sessions, - sessions, - queue, - new DefaultCleanupService( - queue, - new FakeCleanupContentGateway(), - metadata, - sessions, - new RecordingQuotaReclaimGateway(), - Duration.ofMinutes(5), - FileserverMetricsPort.noop(), - new DirectTransactions(), - clock), - accessPolicy, + private final AdminAudit audit = + new AdminAudit( adminPorts, new SafeFileFingerprint("test-fingerprint-key!".getBytes(StandardCharsets.UTF_8)), - new DirectTransactions(), clock); + private final GetRuntimeCapabilitiesApplicationUseCase capabilities = + new GetRuntimeCapabilitiesApplicationUseCase(adminPorts, accessPolicy); + + private final GetStorageHealthApplicationUseCase storageHealth = + new GetStorageHealthApplicationUseCase(adminPorts, accessPolicy); + + private final ReconcileOrphansApplicationUseCase reconcile = + new ReconcileOrphansApplicationUseCase( + adminPorts, queue, accessPolicy, audit, new DirectTransactions()); + + private final ReverifyFileApplicationUseCase reverify = + new ReverifyFileApplicationUseCase(metadata, accessPolicy, audit, new DirectTransactions()); + + private final ForceDeleteFileApplicationUseCase forceDelete = + new ForceDeleteFileApplicationUseCase( + metadata, sessions, sessions, queue, accessPolicy, audit, new DirectTransactions()); + @Test void capabilitiesNeverDiscloseAPhysicalRoot() { - RuntimeCapabilityReport report = admin.capabilities(FileserverFixtures.context()); + RuntimeCapabilityReport report = + capabilities.handle(new GetRuntimeCapabilitiesQuery(FileserverFixtures.context())); assertThat(report.storageType()).isEqualTo("LOCAL"); assertThat(report.filesystemProfile()).isEqualTo("linux-ext4"); @@ -86,7 +86,8 @@ class FileserverAdminServiceTest { @Test void storageHealthReportsProportionsRatherThanPaths() { - StorageHealthReport health = admin.storageHealth(FileserverFixtures.context()); + StorageHealthReport health = + storageHealth.handle(new GetStorageHealthQuery(FileserverFixtures.context())); assertThat(health.usedFraction()).isEqualTo(0.6); assertThat(health.toString()).doesNotContain("/var").doesNotContain("mount"); @@ -99,7 +100,9 @@ class FileserverAdminServiceTest { accessPolicy.deny(FileOperation.ADMIN_READ); // when - Throwable failure = catchThrowable(() -> admin.storageHealth(FileserverFixtures.context())); + Throwable failure = + catchThrowable( + () -> storageHealth.handle(new GetStorageHealthQuery(FileserverFixtures.context()))); // then assertThat(failure) @@ -112,7 +115,7 @@ class FileserverAdminServiceTest { adminPorts.addOrphan(new OrphanObject(ORPHAN_KEY, 100, FileserverFixtures.NOW, "fp-1")); OrphanReconcileReport report = - admin.reconcileOrphans(OrphanReconcileCommand.dryRun(100), FileserverFixtures.context()); + reconcile.handle(OrphanReconcileCommand.dryRun(100, FileserverFixtures.context())); assertThat(report.dryRun()).isTrue(); assertThat(report.candidates()).hasSize(1); @@ -128,9 +131,14 @@ class FileserverAdminServiceTest { ContentKey.of("aa/bb/orphan-object-0002"), 100, FileserverFixtures.NOW, "fp-2")); OrphanReconcileReport report = - admin.reconcileOrphans( - new OrphanReconcileCommand(false, 100, 1L << 20, List.of("fp-1"), "OPERATOR_APPLY"), - FileserverFixtures.context()); + reconcile.handle( + new OrphanReconcileCommand( + false, + 100, + 1L << 20, + List.of("fp-1"), + "OPERATOR_APPLY", + FileserverFixtures.context())); assertThat(report.deleted()).isEqualTo(1); assertThat(report.skippedFingerprintMismatch()).isEqualTo(1); @@ -145,9 +153,14 @@ class FileserverAdminServiceTest { ContentKey.of("aa/bb/orphan-object-0002"), 100, FileserverFixtures.NOW, "fp-2")); OrphanReconcileReport report = - admin.reconcileOrphans( - new OrphanReconcileCommand(false, 100, 100, List.of("fp-1", "fp-2"), "OPERATOR_APPLY"), - FileserverFixtures.context()); + reconcile.handle( + new OrphanReconcileCommand( + false, + 100, + 100, + List.of("fp-1", "fp-2"), + "OPERATOR_APPLY", + FileserverFixtures.context())); assertThat(report.deleted()).isEqualTo(1); assertThat(report.reclaimedBytes()).isEqualTo(100); @@ -156,7 +169,9 @@ class FileserverAdminServiceTest { @Test void anApplyWithoutFingerprintsCannotEvenBeConstructed() { assertThatThrownBy( - () -> new OrphanReconcileCommand(false, 100, 1024, List.of(), "OPERATOR_APPLY")) + () -> + new OrphanReconcileCommand( + false, 100, 1024, List.of(), "OPERATOR_APPLY", FileserverFixtures.context())) .isInstanceOf(IllegalArgumentException.class); } @@ -164,7 +179,10 @@ class FileserverAdminServiceTest { void reverifyOnlyAcceptsAQuarantinedFileAndAuditsTheRefusal() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); - assertThatThrownBy(() -> admin.reverify(ready.fileId(), FileserverFixtures.context())) + assertThatThrownBy( + () -> + reverify.handle( + new ReverifyFileCommand(ready.fileId(), FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(adminPorts.auditTrail()) @@ -180,7 +198,7 @@ class FileserverAdminServiceTest { void reverifyMovesAQuarantinedFileBackIntoVerification() { FileRecord quarantined = quarantinedRecord(); - admin.reverify(quarantined.fileId(), FileserverFixtures.context()); + reverify.handle(new ReverifyFileCommand(quarantined.fileId(), FileserverFixtures.context())); assertThat(metadata.find(quarantined.fileId()).orElseThrow().state()) .isEqualTo(FileState.VERIFYING); @@ -193,9 +211,9 @@ class FileserverAdminServiceTest { void forceDeleteRequiresTheSecondAuthorityAndIsAudited() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); - admin.forceDelete( - new ForceDeleteCommand(ready.fileId(), "LEGAL_TAKEDOWN_2026_08"), - FileserverFixtures.context()); + forceDelete.handle( + new ForceDeleteCommand( + ready.fileId(), "LEGAL_TAKEDOWN_2026_08", FileserverFixtures.context())); assertThat(accessPolicy.invocations()).containsExactly(FileOperation.ADMIN_FORCE_DELETE); assertThat(metadata.find(ready.fileId()).orElseThrow().state()).isEqualTo(FileState.DELETING); @@ -216,9 +234,9 @@ class FileserverAdminServiceTest { FileRecord uploading = ReadyFileFixture.uploading(metadata, SIZE, DIGEST); // when - admin.forceDelete( - new ForceDeleteCommand(uploading.fileId(), "LEGAL_TAKEDOWN_2026_08"), - FileserverFixtures.context()); + forceDelete.handle( + new ForceDeleteCommand( + uploading.fileId(), "LEGAL_TAKEDOWN_2026_08", FileserverFixtures.context())); // then assertThat(metadata.find(uploading.fileId()).orElseThrow().state()) @@ -240,9 +258,9 @@ class FileserverAdminServiceTest { FileserverFixtures.NOW.plusSeconds(3600))); // when - admin.forceDelete( - new ForceDeleteCommand(uploading.fileId(), "LEGAL_TAKEDOWN_2026_08"), - FileserverFixtures.context()); + forceDelete.handle( + new ForceDeleteCommand( + uploading.fileId(), "LEGAL_TAKEDOWN_2026_08", FileserverFixtures.context())); // then assertThat( @@ -263,9 +281,9 @@ class FileserverAdminServiceTest { assertThatThrownBy( () -> - admin.forceDelete( - new ForceDeleteCommand(ready.fileId(), "LEGAL_TAKEDOWN_2026_08"), - FileserverFixtures.context())) + forceDelete.handle( + new ForceDeleteCommand( + ready.fileId(), "LEGAL_TAKEDOWN_2026_08", FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(ready.fileId()).orElseThrow().state()).isEqualTo(FileState.READY); @@ -275,7 +293,10 @@ class FileserverAdminServiceTest { void aForceDeleteWithoutAReasonCannotBeConstructed() { assertThatThrownBy( () -> - new ForceDeleteCommand(FileId.parse("00000000-0000-0000-0000-000000000001"), " ")) + new ForceDeleteCommand( + FileId.parse("00000000-0000-0000-0000-000000000001"), + " ", + FileserverFixtures.context())) .isInstanceOf(IllegalArgumentException.class); } @@ -283,9 +304,9 @@ class FileserverAdminServiceTest { void theAuditTrailCarriesAnActorFingerprintRatherThanAPrincipal() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); - admin.forceDelete( - new ForceDeleteCommand(ready.fileId(), "LEGAL_TAKEDOWN_2026_08"), - FileserverFixtures.context()); + forceDelete.handle( + new ForceDeleteCommand( + ready.fileId(), "LEGAL_TAKEDOWN_2026_08", FileserverFixtures.context())); assertThat(adminPorts.auditTrail()) .singleElement() diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadApplicationServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java similarity index 67% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadApplicationServiceTest.java rename to src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java index 88338928..52728bb6 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadApplicationServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/download/DownloadUseCasesTest.java @@ -9,6 +9,10 @@ import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; import dev.caskeleton.application.fileserver.api.error.FileserverException; import dev.caskeleton.application.fileserver.api.metadata.FileRecord; import dev.caskeleton.application.fileserver.api.security.FileOperation; +import dev.caskeleton.application.fileserver.port.in.DescribeFileQuery; +import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentQuery; +import dev.caskeleton.application.fileserver.port.in.PrepareDownloadQuery; +import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeDownloadContentGateway; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; @@ -19,7 +23,7 @@ import java.nio.channels.ReadableByteChannel; import java.util.UUID; import org.junit.jupiter.api.Test; -class DownloadApplicationServiceTest { +class DownloadUseCasesTest { private static final String DIGEST = "b".repeat(64); private static final long SIZE = 10; @@ -28,15 +32,19 @@ class DownloadApplicationServiceTest { private final FakeDownloadContentGateway content = new FakeDownloadContentGateway(); private final FakeFileAccessPolicy accessPolicy = new FakeFileAccessPolicy(); - private final DownloadApplicationService service = - new DefaultDownloadApplicationService(metadata, content, accessPolicy); + private final PrepareDownloadApplicationUseCase prepare = + new PrepareDownloadApplicationUseCase(metadata, accessPolicy, new DirectTransactions()); + private final DescribeFileApplicationUseCase describeFile = + new DescribeFileApplicationUseCase(metadata, accessPolicy, new DirectTransactions()); + private final OpenDownloadContentApplicationUseCase open = + new OpenDownloadContentApplicationUseCase(content); @Test void readyFileExposesOnlyImmutableContentFacts() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); DownloadDescriptor descriptor = - service.describe(DownloadRequest.of(ready.fileId()), FileserverFixtures.context()); + prepare.handle(new PrepareDownloadQuery(ready.fileId(), FileserverFixtures.context())); assertThat(descriptor.representation().length()).isEqualTo(SIZE); assertThat(descriptor.representation().sha256()).isEqualTo(DIGEST); @@ -51,8 +59,8 @@ class DownloadApplicationServiceTest { assertThatThrownBy( () -> - service.describe( - DownloadRequest.of(verifying.fileId()), FileserverFixtures.context())) + prepare.handle( + new PrepareDownloadQuery(verifying.fileId(), FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(content.neverOpened()).isTrue(); @@ -64,8 +72,8 @@ class DownloadApplicationServiceTest { assertThatThrownBy( () -> - service.describe( - DownloadRequest.of(verifying.fileId()), FileserverFixtures.context())) + prepare.handle( + new PrepareDownloadQuery(verifying.fileId(), FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(content.neverOpened()).isTrue(); @@ -75,8 +83,9 @@ class DownloadApplicationServiceTest { void unknownFileIsNotFound() { assertThatThrownBy( () -> - service.describe( - DownloadRequest.of(FileId.of(UUID.randomUUID())), FileserverFixtures.context())) + prepare.handle( + new PrepareDownloadQuery( + FileId.of(UUID.randomUUID()), FileserverFixtures.context()))) .isInstanceOf(FileNotFoundException.class); } @@ -86,10 +95,11 @@ class DownloadApplicationServiceTest { content.store(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); DownloadDescriptor descriptor = - service.describe(DownloadRequest.of(ready.fileId()), FileserverFixtures.context()); + prepare.handle(new PrepareDownloadQuery(ready.fileId(), FileserverFixtures.context())); ByteRange range = ByteRange.of(2, 4); ByteBuffer buffer = ByteBuffer.allocate(8); - try (ReadableByteChannel channel = service.openContent(descriptor, range)) { + try (ReadableByteChannel channel = + open.handle(new OpenDownloadContentQuery(descriptor, range))) { channel.read(buffer); } @@ -101,7 +111,10 @@ class DownloadApplicationServiceTest { void metadataReadIsItsOwnAuthorizedOperation() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); - assertThat(service.describeFile(ready.fileId(), FileserverFixtures.context()).isDownloadable()) + assertThat( + describeFile + .handle(new DescribeFileQuery(ready.fileId(), FileserverFixtures.context())) + .isDownloadable()) .isTrue(); assertThat(accessPolicy.invocations()).containsExactly(FileOperation.READ_METADATA); } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java similarity index 75% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleServiceTest.java rename to src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java index 41e1e401..95d09261 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java @@ -14,6 +14,9 @@ import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; +import dev.caskeleton.application.fileserver.port.in.CopyFileCommand; +import dev.caskeleton.application.fileserver.port.in.DeleteFileCommand; +import dev.caskeleton.application.fileserver.port.in.MoveFileCommand; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeCopyContentGateway; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; @@ -32,7 +35,7 @@ import java.util.OptionalLong; import java.util.UUID; import org.junit.jupiter.api.Test; -class FileLifecycleServiceTest { +class FileLifecycleUseCasesTest { private static final String DIGEST = "f".repeat(64); private static final long SIZE = 10; @@ -43,25 +46,32 @@ class FileLifecycleServiceTest { private final InMemoryCleanupQueue cleanup = new InMemoryCleanupQueue(); private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); - private final FileLifecycleService service = - new DefaultFileLifecycleService( + private final DirectTransactions transactions = new DirectTransactions(); + + private final DeleteFileApplicationUseCase delete = + new DeleteFileApplicationUseCase( + metadata, accessPolicy, cleanup, sessions, sessions, transactions); + + private final CopyFileApplicationUseCase copy = + new CopyFileApplicationUseCase( metadata, copyGateway, accessPolicy, OriginalFilenamePolicy.standard(), - cleanup, - sessions, - sessions, new SequentialUploadIdentifierFactory(), - new DirectTransactions(), + transactions, Clock.fixed(FileserverFixtures.NOW, ZoneOffset.UTC)); + private final MoveFileApplicationUseCase move = + new MoveFileApplicationUseCase(metadata, accessPolicy, transactions); + @Test void logicalDeleteBlocksDownloadBeforePhysicalDeleteCompletes() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); DeleteOutcome outcome = - service.delete(ready.fileId(), Optional.empty(), FileserverFixtures.context()); + delete.handle( + new DeleteFileCommand(ready.fileId(), Optional.empty(), FileserverFixtures.context())); assertThat(outcome.physicalCleanupScheduled()).isTrue(); FileRecord current = metadata.find(ready.fileId()).orElseThrow(); @@ -77,7 +87,9 @@ class FileLifecycleServiceTest { FileRecord uploading = ReadyFileFixture.uploading(metadata, SIZE, DIGEST); DeleteOutcome outcome = - service.delete(uploading.fileId(), Optional.empty(), FileserverFixtures.context()); + delete.handle( + new DeleteFileCommand( + uploading.fileId(), Optional.empty(), FileserverFixtures.context())); assertThat(outcome.physicalCleanupScheduled()).isFalse(); assertThat(metadata.find(uploading.fileId()).orElseThrow().state()) @@ -99,7 +111,8 @@ class FileLifecycleServiceTest { FileserverFixtures.NOW.plusSeconds(3600))); // when - service.delete(uploading.fileId(), Optional.empty(), FileserverFixtures.context()); + delete.handle( + new DeleteFileCommand(uploading.fileId(), Optional.empty(), FileserverFixtures.context())); // then assertThat( @@ -119,7 +132,9 @@ class FileLifecycleServiceTest { assertThatThrownBy( () -> - service.delete(verifying.fileId(), Optional.empty(), FileserverFixtures.context())) + delete.handle( + new DeleteFileCommand( + verifying.fileId(), Optional.empty(), FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(verifying.fileId()).orElseThrow().state()) @@ -132,8 +147,9 @@ class FileLifecycleServiceTest { assertThatThrownBy( () -> - service.delete( - ready.fileId(), Optional.of("\"stale\""), FileserverFixtures.context())) + delete.handle( + new DeleteFileCommand( + ready.fileId(), Optional.of("\"stale\""), FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(ready.fileId()).orElseThrow().state()).isEqualTo(FileState.READY); @@ -146,7 +162,10 @@ class FileLifecycleServiceTest { accessPolicy.deny(FileOperation.DELETE); assertThatThrownBy( - () -> service.delete(ready.fileId(), Optional.empty(), FileserverFixtures.context())) + () -> + delete.handle( + new DeleteFileCommand( + ready.fileId(), Optional.empty(), FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(ready.fileId()).orElseThrow().state()).isEqualTo(FileState.READY); @@ -158,13 +177,13 @@ class FileLifecycleServiceTest { copyGateway.copiesContentOf(SIZE, DIGEST); FileView copied = - service.copy( + copy.handle( new CopyFileCommand( source.fileId(), StorageNamespace.of("tenant-b"), Optional.of("copy.bin"), - Optional.empty()), - FileserverFixtures.context()); + Optional.empty(), + FileserverFixtures.context())); assertThat(copied.state()).isEqualTo(FileState.READY); assertThat(copied.fileId()).isNotEqualTo(source.fileId()); @@ -180,13 +199,13 @@ class FileLifecycleServiceTest { assertThatThrownBy( () -> - service.copy( + copy.handle( new CopyFileCommand( source.fileId(), StorageNamespace.of("tenant-b"), Optional.empty(), - Optional.empty()), - FileserverFixtures.context())) + Optional.empty(), + FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(source.fileId()).orElseThrow().state()).isEqualTo(FileState.READY); @@ -198,13 +217,13 @@ class FileLifecycleServiceTest { assertThatThrownBy( () -> - service.copy( + copy.handle( new CopyFileCommand( verifying.fileId(), StorageNamespace.of("tenant-b"), Optional.empty(), - Optional.empty()), - FileserverFixtures.context())) + Optional.empty(), + FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(copyGateway.copies()).isEmpty(); @@ -215,11 +234,12 @@ class FileLifecycleServiceTest { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); FileView moved = - service.move( - ready.fileId(), - StorageNamespace.of("tenant-b"), - Optional.of(DIGEST), - FileserverFixtures.context()); + move.handle( + new MoveFileCommand( + ready.fileId(), + StorageNamespace.of("tenant-b"), + Optional.of(DIGEST), + FileserverFixtures.context())); assertThat(moved.descriptor().namespace()).isEqualTo(StorageNamespace.of("tenant-b")); assertThat(metadata.find(ready.fileId()).orElseThrow().contentKey()) @@ -230,12 +250,14 @@ class FileLifecycleServiceTest { @Test void everyLifecycleOperationConsultsItsOwnAccessOperation() { FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); - service.move( - ready.fileId(), - StorageNamespace.of("tenant-b"), - Optional.empty(), - FileserverFixtures.context()); - service.delete(ready.fileId(), Optional.empty(), FileserverFixtures.context()); + move.handle( + new MoveFileCommand( + ready.fileId(), + StorageNamespace.of("tenant-b"), + Optional.empty(), + FileserverFixtures.context())); + delete.handle( + new DeleteFileCommand(ready.fileId(), Optional.empty(), FileserverFixtures.context())); assertThat(accessPolicy.invocations()) .containsExactly(FileOperation.MOVE, FileOperation.DELETE); @@ -244,10 +266,13 @@ class FileLifecycleServiceTest { @Test void deletingAnAlreadyDeletedRecordIsIdempotent() { FileRecord uploading = ReadyFileFixture.uploading(metadata, SIZE, DIGEST); - service.delete(uploading.fileId(), Optional.empty(), FileserverFixtures.context()); + delete.handle( + new DeleteFileCommand(uploading.fileId(), Optional.empty(), FileserverFixtures.context())); DeleteOutcome second = - service.delete(uploading.fileId(), Optional.empty(), FileserverFixtures.context()); + delete.handle( + new DeleteFileCommand( + uploading.fileId(), Optional.empty(), FileserverFixtures.context())); assertThat(second.physicalCleanupScheduled()).isFalse(); assertThat(metadata.find(uploading.fileId()).orElseThrow().state()) diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java index 0c28f739..3a97c75e 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/InMemoryUploadSessionStore.java @@ -39,6 +39,17 @@ public final class InMemoryUploadSessionStore this.now = instant; } + /** + * Records a session in a state a test built directly, as if earlier appends had produced it. + * + * @param session the session + * @return the same session + */ + public UploadSession seed(UploadSession session) { + sessions.put(session.uploadId(), session); + return session; + } + @Override public UploadSession create(UploadSessionDraft draft) { UploadSession session = diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java deleted file mode 100644 index b1a0cc2e..00000000 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.UploadId; -import dev.caskeleton.application.fileserver.api.error.AmbiguousCompletionException; -import dev.caskeleton.application.fileserver.api.metadata.UploadSession; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.api.transfer.UploadMode; -import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; -import java.io.ByteArrayInputStream; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.util.Optional; -import java.util.OptionalLong; -import java.util.UUID; -import org.junit.jupiter.api.Test; - -class DefaultSingleShotUploadServiceTest { - - private static final UploadId UPLOAD_ID = - UploadId.of(UUID.fromString("00000000-0000-7000-8000-000000000041")); - private static final FileId FILE_ID = - FileId.of(UUID.fromString("00000000-0000-7000-8000-000000000042")); - - @Test - void appendFailureCancelsTheCreatedUploadBeforePropagating() { - RuntimeException failure = new IllegalStateException("append failed"); - RecordingUploadService upload = new RecordingUploadService(failure); - DefaultSingleShotUploadService service = - new DefaultSingleShotUploadService(upload, new NeverFinalize()); - - assertThatThrownBy(() -> upload(service)).isSameAs(failure); - assertThat(upload.cancelCalls).isEqualTo(1); - } - - @Test - void ambiguousFinalizeIsLeftForReconciliationInsteadOfBlindCancellation() { - RecordingUploadService upload = new RecordingUploadService(null); - AmbiguousCompletionException ambiguous = - AmbiguousCompletionException.forUpload("publish outcome unknown", UPLOAD_ID); - DefaultSingleShotUploadService service = - new DefaultSingleShotUploadService(upload, new AmbiguousFinalize(ambiguous)); - - assertThatThrownBy(() -> upload(service)).isSameAs(ambiguous); - assertThat(upload.cancelCalls).isZero(); - } - - private static void upload(DefaultSingleShotUploadService service) { - try (ReadableByteChannel content = - Channels.newChannel(new ByteArrayInputStream(new byte[] {1, 2, 3}))) { - service.upload( - new CreateUploadRequest( - "report.bin", - Optional.of("application/octet-stream"), - OptionalLong.of(3), - Optional.empty(), - UploadMode.SINGLE_SHOT), - content, - 3, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context()); - } catch (java.io.IOException impossible) { - throw new IllegalStateException(impossible); - } - } - - private static final class RecordingUploadService implements UploadApplicationService { - private final RuntimeException appendFailure; - private int cancelCalls; - - RecordingUploadService(RuntimeException appendFailure) { - this.appendFailure = appendFailure; - } - - @Override - public UploadSessionView create(CreateUploadRequest request, RequestContext context) { - return new UploadSessionView( - UPLOAD_ID, FILE_ID, 0, OptionalLong.of(3), FileserverFixtures.NOW.plusSeconds(3600)); - } - - @Override - public AppendUploadResult append( - UploadId uploadId, - long expectedOffset, - ReadableByteChannel content, - long contentLength, - Optional expectedChunkSha256, - RequestContext context) { - if (appendFailure != null) { - throw appendFailure; - } - return new AppendUploadResult(3, 3, FileserverFixtures.DIGEST); - } - - @Override - public UploadSessionView status(UploadId uploadId, RequestContext context) { - throw new UnsupportedOperationException(); - } - - @Override - public void cancel(UploadId uploadId, RequestContext context) { - cancelCalls++; - } - } - - private static final class NeverFinalize implements FinalizeUploadService { - @Override - public FileView finalizeUpload( - UploadSession session, FinalizeUploadRequest request, RequestContext context) { - throw new AssertionError("finalize must not run after append failure"); - } - - @Override - public FileView finalizeUpload( - UploadId uploadId, FinalizeUploadRequest request, RequestContext context) { - throw new AssertionError("finalize must not run after append failure"); - } - } - - private static final class AmbiguousFinalize implements FinalizeUploadService { - private final AmbiguousCompletionException failure; - - AmbiguousFinalize(AmbiguousCompletionException failure) { - this.failure = failure; - } - - @Override - public FileView finalizeUpload( - UploadSession session, FinalizeUploadRequest request, RequestContext context) { - throw new UnsupportedOperationException(); - } - - @Override - public FileView finalizeUpload( - UploadId uploadId, FinalizeUploadRequest request, RequestContext context) { - throw failure; - } - } -} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java similarity index 75% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java rename to src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java index fbf7fdfc..0e751b9c 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadApplicationUseCaseTest.java @@ -16,6 +16,7 @@ import dev.caskeleton.application.fileserver.api.metadata.FileRecordMutation; import dev.caskeleton.application.fileserver.api.metadata.UploadSession; import dev.caskeleton.application.fileserver.api.security.FileOperation; import dev.caskeleton.application.fileserver.api.security.VerificationResult; +import dev.caskeleton.application.fileserver.port.in.FinalizeUploadCommand; import dev.caskeleton.application.fileserver.testkit.DirectTransactions; import dev.caskeleton.application.fileserver.testkit.FakeFileAccessPolicy; import dev.caskeleton.application.fileserver.testkit.FakeQuotaCommitGateway; @@ -32,7 +33,7 @@ import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -class FinalizeUploadServiceTest { +class FinalizeUploadApplicationUseCaseTest { private final InMemoryFileMetadataStore metadata = new InMemoryFileMetadataStore(); private final InMemoryUploadSessionStore sessions = new InMemoryUploadSessionStore(); @@ -44,12 +45,12 @@ class FinalizeUploadServiceTest { private final DirectTransactions transactions = new DirectTransactions(); private VerificationResult verdict = VerificationResult.accept("ALL_CHECKS_PASSED"); - private FinalizeUploadService service; + private FinalizeUploadApplicationUseCase service; @BeforeEach void createService() { service = - new DefaultFinalizeUploadService( + new FinalizeUploadApplicationUseCase( metadata, sessions, content, @@ -68,10 +69,11 @@ class FinalizeUploadServiceTest { UploadSession session = uploadedSession(10); FileView result = - service.finalizeUpload( - session, - new FinalizeUploadRequest(Optional.of(FileserverFixtures.DIGEST), false), - FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + new FinalizeUploadRequest(Optional.of(FileserverFixtures.DIGEST), false), + FileserverFixtures.context())); assertThat(result.state()).isEqualTo(FileState.READY); FileRecord stored = metadata.find(result.fileId()).orElseThrow(); @@ -89,10 +91,11 @@ class FinalizeUploadServiceTest { assertThatThrownBy( () -> - service.finalizeUpload( - session, - new FinalizeUploadRequest(Optional.of("0".repeat(64)), false), - FileserverFixtures.context())) + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + new FinalizeUploadRequest(Optional.of("0".repeat(64)), false), + FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(session.fileId()).orElseThrow().state()).isEqualTo(FileState.REJECTED); @@ -104,8 +107,11 @@ class FinalizeUploadServiceTest { void quotaIsCommittedOnlyAfterTheReadyTransition() { UploadSession session = uploadedSession(10); - service.finalizeUpload( - session, FinalizeUploadRequest.synchronousWithoutDigest(), FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); assertThat(quota.committedBytes()).isEqualTo(10); assertThat(content.leaseReleases()).isEqualTo(1); @@ -117,10 +123,11 @@ class FinalizeUploadServiceTest { UploadSession session = uploadedSession(10); FileView result = - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); assertThat(result.state()).isEqualTo(FileState.REJECTED); assertThat(result.isDownloadable()).isFalse(); @@ -136,10 +143,11 @@ class FinalizeUploadServiceTest { assertThatThrownBy( () -> - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context())) + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(metadata.find(session.fileId()).orElseThrow().state()).isEqualTo(FileState.REJECTED); @@ -151,10 +159,11 @@ class FinalizeUploadServiceTest { UploadSession session = uploadedSession(10); FileView result = - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); assertThat(result.state()).isEqualTo(FileState.QUARANTINED); assertThat(result.isDownloadable()).isFalse(); @@ -169,8 +178,11 @@ class FinalizeUploadServiceTest { UploadSession session = uploadedSession(10); // when - service.finalizeUpload( - session, FinalizeUploadRequest.synchronousWithoutDigest(), FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); // then assertThat(cleanup.queued()).isEmpty(); @@ -186,10 +198,11 @@ class FinalizeUploadServiceTest { Throwable failure = catchThrowable( () -> - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context())); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))); // then assertThat(failure) @@ -208,10 +221,11 @@ class FinalizeUploadServiceTest { Throwable failure = catchThrowable( () -> - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context())); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))); // then assertThat(metadata.find(session.fileId()).orElseThrow().contentKey()) @@ -232,10 +246,11 @@ class FinalizeUploadServiceTest { Throwable failure = catchThrowable( () -> - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context())); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))); // then assertThat(recovery.reasons()) @@ -249,10 +264,11 @@ class FinalizeUploadServiceTest { UploadSession session = uploadedSession(10); FileView result = - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); assertThat(result.state()).isEqualTo(FileState.VERIFYING); assertThat(result.isDownloadable()).isFalse(); @@ -265,10 +281,11 @@ class FinalizeUploadServiceTest { assertThatThrownBy( () -> - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context())) + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))) .isInstanceOf(FileserverException.class); assertThat(content.publishedCount()).isZero(); @@ -283,10 +300,11 @@ class FinalizeUploadServiceTest { assertThatThrownBy( () -> - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context())) + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()))) .isInstanceOf(AmbiguousCompletionException.class) .satisfies( failure -> { @@ -309,14 +327,15 @@ class FinalizeUploadServiceTest { // given FileId fileId = FileId.of(UUID.randomUUID()); metadata.insert(FileserverFixtures.draft(fileId, 10)); - UploadSession session = FileserverFixtures.session(fileId, 10, 10); + UploadSession session = sessions.seed(FileserverFixtures.session(fileId, 10, 10)); // when FileView result = - service.finalizeUpload( - session, - FinalizeUploadRequest.synchronousWithoutDigest(), - FileserverFixtures.context()); + service.handle( + new FinalizeUploadCommand( + session.uploadId(), + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context())); // then assertThat(result.state()).isEqualTo(FileState.READY); @@ -335,7 +354,7 @@ class FinalizeUploadServiceTest { FileState.CREATED, FileState.UPLOADING, FileRecordMutation.none()); - return FileserverFixtures.session(fileId, declaredLength, committedOffset); + return sessions.seed(FileserverFixtures.session(fileId, declaredLength, committedOffset)); } /** Moves the record to VERIFYING so the injected failure lands on the READY commit. */ diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java similarity index 96% rename from src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java rename to src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java index 0eb234d2..04abdfe9 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/ResumableUploadUseCasesTest.java @@ -22,7 +22,6 @@ import dev.caskeleton.application.fileserver.api.security.RequestContext; import dev.caskeleton.application.fileserver.api.transfer.UploadMode; import dev.caskeleton.application.fileserver.cleanup.CleanupType; import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; -import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; import dev.caskeleton.application.fileserver.quota.StorageUsagePort; import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties; @@ -52,7 +51,7 @@ import java.util.OptionalLong; import java.util.Set; import org.junit.jupiter.api.Test; -class UploadApplicationServiceTest { +class ResumableUploadUseCasesTest { private static final long MAX_FILE = 100L * 1024 * 1024; @@ -64,7 +63,7 @@ class UploadApplicationServiceTest { private final InMemoryCleanupQueue cleanup = new InMemoryCleanupQueue(); private final DirectTransactions transactions = new DirectTransactions(); - private final UploadApplicationService service = serviceAt(FileserverFixtures.NOW); + private final UploadUseCases service = serviceAt(FileserverFixtures.NOW); @Test void authorizationRunsBeforeQuotaAndStorageMutation() { @@ -107,7 +106,7 @@ class UploadApplicationServiceTest { new TransferAdmissionProperties(16, 1, 64, 0.70, 0.85), StorageUsagePort.unknown(), MAX_FILE); - UploadApplicationService narrow = service(FileserverFixtures.NOW, admission); + UploadUseCases narrow = service(FileserverFixtures.NOW, admission); try (TransferPermit namespaceFull = admission.acquireUpload(QuotaScope.ofNamespace(FileserverFixtures.NAMESPACE.value()), 1)) { @@ -362,7 +361,7 @@ class UploadApplicationServiceTest { @Test void anExpiredUploadCanNoLongerBeAppended() { UploadSessionView created = service.create(createRequest(), FileserverFixtures.context()); - UploadApplicationService afterExpiry = serviceAt(FileserverFixtures.NOW.plusSeconds(7200)); + UploadUseCases afterExpiry = serviceAt(FileserverFixtures.NOW.plusSeconds(7200)); assertThatThrownBy( () -> @@ -427,17 +426,16 @@ class UploadApplicationServiceTest { .isInstanceOf(dev.caskeleton.application.fileserver.api.error.FileNotFoundException.class); } - private UploadApplicationService serviceAt(java.time.Instant instant) { + private UploadUseCases serviceAt(java.time.Instant instant) { return service( instant, new TransferAdmissionController( TransferAdmissionProperties.standard(), StorageUsagePort.unknown(), MAX_FILE)); } - private UploadApplicationService service( - java.time.Instant instant, TransferAdmissionController admission) { + private UploadUseCases service(java.time.Instant instant, TransferAdmissionController admission) { Clock clock = Clock.fixed(instant, ZoneOffset.UTC); - return new DefaultUploadApplicationService( + return UploadUseCases.over( new UploadStores(metadata, sessions, cleanup), new UploadPolicies( accessPolicy, @@ -452,7 +450,6 @@ class UploadApplicationServiceTest { quota, admission, new SequentialUploadIdentifierFactory(), - FileserverMetricsPort.noop(), transactions, clock); } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java new file mode 100644 index 00000000..531c01e3 --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadFileApplicationUseCaseTest.java @@ -0,0 +1,98 @@ +package dev.caskeleton.application.fileserver.upload; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.fileserver.api.FileId; +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.error.AmbiguousCompletionException; +import dev.caskeleton.application.fileserver.api.transfer.UploadMode; +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.FinalizeUploadUseCase; +import dev.caskeleton.application.fileserver.port.in.UploadFileCommand; +import dev.caskeleton.application.fileserver.testkit.FileserverFixtures; +import java.io.ByteArrayInputStream; +import java.nio.channels.Channels; +import java.util.List; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import org.junit.jupiter.api.Test; + +class UploadFileApplicationUseCaseTest { + + private static final UploadId UPLOAD_ID = + UploadId.of(UUID.fromString("00000000-0000-7000-8000-000000000041")); + private static final FileId FILE_ID = + FileId.of(UUID.fromString("00000000-0000-7000-8000-000000000042")); + + private final List cancelled = new CopyOnWriteArrayList<>(); + private final CreateUploadUseCase create = + command -> + new UploadSessionView( + UPLOAD_ID, FILE_ID, 0, OptionalLong.of(3), FileserverFixtures.NOW.plusSeconds(3600)); + private final CancelUploadUseCase cancel = + command -> { + cancelled.add(command.uploadId()); + return null; + }; + + @Test + void appendFailureCancelsTheCreatedUploadBeforePropagating() { + // given + RuntimeException failure = new IllegalStateException("append failed"); + AppendUploadUseCase append = + command -> { + throw failure; + }; + FinalizeUploadUseCase finalizer = + command -> { + throw new AssertionError("finalize must not run after append failure"); + }; + UploadFileApplicationUseCase useCase = + new UploadFileApplicationUseCase(create, append, finalizer, cancel); + + // when + Throwable thrown = catchThrowable(() -> useCase.handle(command())); + + // then + assertThat(List.of(thrown, cancelled)).containsExactly(failure, List.of(UPLOAD_ID)); + } + + @Test + void ambiguousFinalizeIsLeftForReconciliationInsteadOfBlindCancellation() { + // given + AmbiguousCompletionException ambiguous = + AmbiguousCompletionException.forUpload("publish outcome unknown", UPLOAD_ID); + AppendUploadUseCase append = command -> new AppendUploadResult(3, 3, FileserverFixtures.DIGEST); + FinalizeUploadUseCase finalizer = + command -> { + throw ambiguous; + }; + UploadFileApplicationUseCase useCase = + new UploadFileApplicationUseCase(create, append, finalizer, cancel); + + // when + Throwable thrown = catchThrowable(() -> useCase.handle(command())); + + // then + assertThat(List.of(thrown, cancelled)).containsExactly(ambiguous, List.of()); + } + + private static UploadFileCommand command() { + return new UploadFileCommand( + new CreateUploadRequest( + "report.bin", + Optional.of("application/octet-stream"), + OptionalLong.of(3), + Optional.empty(), + UploadMode.SINGLE_SHOT), + Channels.newChannel(new ByteArrayInputStream(new byte[] {1, 2, 3})), + 3, + FinalizeUploadRequest.synchronousWithoutDigest(), + FileserverFixtures.context()); + } +} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadUseCases.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadUseCases.java new file mode 100644 index 00000000..5b2381fa --- /dev/null +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadUseCases.java @@ -0,0 +1,92 @@ +package dev.caskeleton.application.fileserver.upload; + +import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; +import dev.caskeleton.application.fileserver.api.security.RequestContext; +import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; +import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; +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.GetUploadStatusQuery; +import dev.caskeleton.application.fileserver.port.in.GetUploadStatusUseCase; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; +import dev.caskeleton.application.transaction.TransactionPort; +import java.nio.channels.ReadableByteChannel; +import java.time.Clock; +import java.util.Optional; + +/** + * The four resumable-upload use cases over one set of fakes, called the way a transport calls them. + * + *

    Each method builds the command and hands it to the use case; nothing else happens here, so a + * test reads as a sequence of client operations rather than a sequence of command constructions. + */ +record UploadUseCases( + CreateUploadUseCase create, + AppendUploadUseCase append, + GetUploadStatusUseCase status, + CancelUploadUseCase cancel) { + + static UploadUseCases over( + UploadStores stores, + UploadPolicies policies, + WriterLeaseCoordinator leases, + UploadStoragePort storage, + FileQuotaPort quota, + TransferAdmissionController admission, + UploadIdentifierPort identifiers, + TransactionPort transactions, + Clock clock) { + return new UploadUseCases( + new CreateUploadApplicationUseCase( + stores, policies, storage, quota, admission, identifiers, transactions, clock), + new AppendUploadApplicationUseCase( + stores, + policies, + leases, + storage, + admission, + FileserverMetricsPort.noop(), + transactions, + clock), + new GetUploadStatusApplicationUseCase(stores, policies.access(), transactions, clock), + new CancelUploadApplicationUseCase(stores, policies.access(), transactions)); + } + + UploadSessionView create(CreateUploadRequest request, RequestContext context) { + return create.handle(new CreateUploadCommand(request, context)); + } + + AppendUploadResult append( + UploadId uploadId, + long expectedOffset, + ReadableByteChannel content, + long contentLength, + Optional expectedChunkSha256, + RequestContext context) { + return append.handle( + new AppendUploadCommand( + uploadId, expectedOffset, content, contentLength, expectedChunkSha256, context)); + } + + AppendUploadResult append( + UploadId uploadId, + long expectedOffset, + ReadableByteChannel content, + long contentLength, + RequestContext context) { + return append(uploadId, expectedOffset, content, contentLength, Optional.empty(), context); + } + + UploadSessionView status(UploadId uploadId, RequestContext context) { + return status.handle(new GetUploadStatusQuery(uploadId, context)); + } + + void cancel(UploadId uploadId, RequestContext context) { + cancel.handle(new CancelUploadCommand(uploadId, context)); + } +} diff --git a/src/build-logic/README.md b/src/build-logic/README.md index a7ca7e3b..0039365e 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -15,9 +15,8 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves | | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | -| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason | +| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | -| `ca.auxiliary-source-set` | extra test source sets | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | | `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | | `ca.bootrun-dotenv` | `bootRun`'s `.env` | diff --git a/src/build-logic/build.gradle b/src/build-logic/build.gradle index 49d64267..82dec59e 100644 --- a/src/build-logic/build.gradle +++ b/src/build-logic/build.gradle @@ -35,10 +35,6 @@ dependencies { gradlePlugin { plugins { - auxiliarySourceSet { - id = 'ca.auxiliary-source-set' - implementationClass = 'dev.caskeleton.buildlogic.auxiliary.AuxiliarySourceSetPlugin' - } apiSurface { id = 'ca.api-surface' implementationClass = 'dev.caskeleton.buildlogic.apisurface.ApiSurfacePlugin' diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetExtension.java deleted file mode 100644 index e4f5c87f..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetExtension.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.buildlogic.auxiliary; - -import java.util.Locale; -import org.gradle.api.Action; -import org.gradle.api.GradleException; -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; -import org.gradle.api.file.FileCollection; -import org.gradle.api.tasks.SourceSet; -import org.gradle.api.tasks.SourceSetContainer; - -public class AuxiliarySourceSetExtension { - private final Project owner; - - public AuxiliarySourceSetExtension(Project owner) { - this.owner = owner; - } - - public void sourceSet(String name, Action configuration) { - AuxiliarySourceSetSpec spec = new AuxiliarySourceSetSpec(name); - configuration.execute(spec); - realize(spec); - } - - private void realize(AuxiliarySourceSetSpec spec) { - SourceSetContainer sourceSets = owner.getExtensions().getByType(SourceSetContainer.class); - SourceSet created = sourceSets.create(spec.getName()); - FileCollection visibleOutputs = owner.files(); - for (String visible : spec.getVisibleOutputs()) { - SourceSet source = sourceSets.findByName(visible); - if (source == null) { - throw new GradleException( - "source set '" - + spec.getName() - + "' in " - + owner.getPath() - + " compiles against '" - + visible - + "', which does not exist. Declare it first — source sets are created in declaration order."); - } - visibleOutputs = visibleOutputs.plus(source.getOutput()); - created.setCompileClasspath(created.getCompileClasspath().plus(source.getOutput())); - } - if (spec.getRuntimeSourceSets().isEmpty()) { - // A source set that compiles against main/test fixtures must see those outputs at runtime, - // but its compile classpath is not a valid runtime classpath: it can contain compileOnly - // analysis/fixture dependencies. Gradle's own runtimeClasspath already carries this source - // set's output plus its runtime configuration, so add only the explicitly visible outputs. - created.setRuntimeClasspath(created.getRuntimeClasspath().plus(visibleOutputs)); - } else { - FileCollection runtimeClasspath = created.getOutput(); - for (String runtimeSourceName : spec.getRuntimeSourceSets()) { - SourceSet runtimeSource = sourceSets.findByName(runtimeSourceName); - if (runtimeSource == null) { - throw new GradleException( - "source set '" - + spec.getName() - + "' in " - + owner.getPath() - + " takes runtime from '" - + runtimeSourceName - + "', which does not exist. Declare it first — source sets are created in declaration order."); - } - runtimeClasspath = runtimeClasspath.plus(runtimeSource.getRuntimeClasspath()); - } - created.setRuntimeClasspath(runtimeClasspath); - } - - for (String suffix : spec.getInheritedTestConfigurations()) { - String capitalized = suffix.substring(0, 1).toUpperCase(Locale.ROOT) + suffix.substring(1); - String inherited = "test" + capitalized; - String own = spec.getName() + capitalized; - Configuration target = owner.getConfigurations().findByName(own); - Configuration source = owner.getConfigurations().findByName(inherited); - if (target == null || source == null) { - throw new GradleException( - "source set '" - + spec.getName() - + "' in " - + owner.getPath() - + " cannot inherit '" - + suffix - + "': expected configurations '" - + own - + "' and '" - + inherited - + "'."); - } - target.extendsFrom(source); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetPlugin.java deleted file mode 100644 index 585e4e1f..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetPlugin.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.buildlogic.auxiliary; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class AuxiliarySourceSetPlugin implements Plugin { - @Override - public void apply(Project project) { - project.getExtensions().create("auxiliarySourceSets", AuxiliarySourceSetExtension.class, project); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetSpec.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetSpec.java deleted file mode 100644 index 6d0c2052..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetSpec.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.buildlogic.auxiliary; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public final class AuxiliarySourceSetSpec { - private final String name; - private final List visibleOutputs = new ArrayList<>(List.of("main")); - private final List inheritedTestConfigurations = - new ArrayList<>(List.of("implementation", "runtimeOnly")); - private final List runtimeSourceSets = new ArrayList<>(); - - public AuxiliarySourceSetSpec(String name) { - this.name = Objects.requireNonNull(name, "name"); - } - - public String getName() { - return name; - } - - public List getVisibleOutputs() { - return List.copyOf(visibleOutputs); - } - - public List getInheritedTestConfigurations() { - return List.copyOf(inheritedTestConfigurations); - } - - public List getRuntimeSourceSets() { - return List.copyOf(runtimeSourceSets); - } - - public void compilesAgainst(String... names) { - visibleOutputs.clear(); - visibleOutputs.addAll(List.of(names)); - } - - public void inherits(String... names) { - inheritedTestConfigurations.clear(); - inheritedTestConfigurations.addAll(List.of(names)); - } - - public void runtimeFrom(String... names) { - runtimeSourceSets.clear(); - runtimeSourceSets.addAll(List.of(names)); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java index 79667132..6736dca9 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java @@ -11,12 +11,14 @@ import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.VersionCatalogsExtension; import org.gradle.api.artifacts.dsl.LockMode; import org.gradle.api.plugins.JavaPluginExtension; +import org.gradle.api.plugins.jvm.JvmTestSuite; import org.gradle.api.provider.ProviderFactory; import org.gradle.api.tasks.bundling.AbstractArchiveTask; import org.gradle.api.tasks.bundling.Jar; import org.gradle.api.tasks.compile.JavaCompile; import org.gradle.api.tasks.testing.Test; import org.gradle.jvm.toolchain.JavaLanguageVersion; +import org.gradle.testing.base.TestingExtension; public final class JavaConventionsPlugin implements Plugin { private static final List COMPILER_ARGS = @@ -145,6 +147,25 @@ public final class JavaConventionsPlugin implements Plugin { project.getTasks().named("test", Test.class).configure(Test::useJUnitPlatform); + // A leaf's extra test source sets are JVM test suites (review BUILD-O3-5 replaced the + // ca.auxiliary-source-set plugin). A suite adds its framework dependency with Gradle's default + // JUnit version, and a version written into a dependency outranks the Spring Boot BOM — so the + // suites would run a different JUnit from `test`. They get the BOM's version instead. + project + .getExtensions() + .getByType(TestingExtension.class) + .getSuites() + .withType(JvmTestSuite.class) + .matching(suite -> !suite.getName().equals("test")) + .configureEach( + suite -> + suite.useJUnitJupiter( + project.provider( + () -> + dependencyManagement + .getManagedVersions() + .get("org.junit.jupiter:junit-jupiter")))); + // The main-branch stage of this leaf (the root `mainCheck` aggregates every leaf's). Empty unless // a convention or the leaf attaches a gate that is not worth a pull request's wait. project diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneExtension.java index 515b5143..f0cfd64a 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneExtension.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneExtension.java @@ -1,6 +1,7 @@ package dev.caskeleton.buildlogic.strictlane; import org.gradle.api.Action; +import org.gradle.api.GradleException; import org.gradle.api.NamedDomainObjectContainer; public class StrictTestLaneExtension { @@ -15,6 +16,13 @@ public class StrictTestLaneExtension { } public void lane(String name, Action configuration) { - lanes.create(name, configuration); + // Configured before it is added, so the plugin's `lanes.all` action sees the declared source + // set (it decides whether the lane is its JVM test suite's own task). + if (lanes.findByName(name) != null) { + throw new GradleException("strict test lane '" + name + "' is declared twice"); + } + StrictTestLaneSpec lane = new StrictTestLaneSpec(name); + configuration.execute(lane); + lanes.add(lane); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java index 1c6bd0e2..e24a578f 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java @@ -13,6 +13,7 @@ import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.testing.Test; +import org.gradle.testing.base.TestingExtension; public final class StrictTestLanePlugin implements Plugin { @Override @@ -32,13 +33,14 @@ public final class StrictTestLanePlugin implements Plugin { lanes.all( lane -> { + // A lane named after the JVM test suite it runs is that suite's own Test task: the suite + // (jvm-test-suite, which replaced ca.auxiliary-source-set) registers it, the lane makes it + // strict. Any other name collision still fails in register(). TaskProvider laneTask = - project - .getTasks() - .register( - lane.getName(), - Test.class, - test -> configureLane(project, java, ownerPath, lane, test)); + isOwnSuiteTask(project, lane) + ? project.getTasks().named(lane.getName(), Test.class) + : project.getTasks().register(lane.getName(), Test.class); + laneTask.configure(test -> configureLane(project, java, ownerPath, lane, test)); project .getGradle() @@ -292,6 +294,14 @@ public final class StrictTestLanePlugin implements Plugin { } } + private static boolean isOwnSuiteTask(Project project, StrictTestLaneSpec lane) { + TestingExtension testing = project.getExtensions().findByType(TestingExtension.class); + return testing != null + && lane.getName().equals(lane.getSourceSet()) + && testing.getSuites().getNames().contains(lane.getName()) + && project.getTasks().getNames().contains(lane.getName()); + } + private static void validateLane(Project project, StrictTestLaneSpec lane) { boolean hasTag = lane.getTag() != null && !lane.getTag().trim().isEmpty(); boolean hasRequired = !lane.getRequiredTests().isEmpty(); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetConventionTest.java deleted file mode 100644 index c2863ab1..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/auxiliary/AuxiliarySourceSetConventionTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package dev.caskeleton.buildlogic.auxiliary; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.gradle.testkit.runner.BuildResult; -import org.gradle.testkit.runner.GradleRunner; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class AuxiliarySourceSetConventionTest { - @TempDir Path projectDir; - - @BeforeEach - void setUp() throws Exception { - Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name='fixture'\n"); - } - - @Test - void declaredSourceSetGetsVisibleOutputsAndSelectedTestConfigurations() throws Exception { - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.auxiliary-source-set' - } - auxiliarySourceSets { - sourceSet('contractTest') { - compilesAgainst 'main' - inherits 'implementation', 'runtimeOnly' - } - } - tasks.register('report') { - doLast { - logger.lifecycle('source=' + (sourceSets.findByName('contractTest') != null)) - logger.lifecycle('extends=' + configurations.contractTestImplementation.extendsFrom*.name.sort()) - } - } - """); - - BuildResult result = runner("report", "--console=plain").build(); - assertTrue(result.getOutput().contains("source=true"), result.getOutput()); - assertTrue(result.getOutput().contains("testImplementation"), result.getOutput()); - } - - @Test - void runtimeCanMirrorAnotherSourceSetWithoutLeakingCompileOnly() throws Exception { - Files.writeString(projectDir.resolve("compile-only-marker.jar"), "marker"); - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.auxiliary-source-set' - } - dependencies { testCompileOnly files('compile-only-marker.jar') } - auxiliarySourceSets { - sourceSet('architectureTest') { - compilesAgainst 'main', 'test' - inherits 'implementation', 'compileOnly', 'runtimeOnly' - runtimeFrom 'test' - } - } - tasks.register('reportRuntime') { - doLast { - def names = sourceSets.architectureTest.runtimeClasspath.files*.name - logger.lifecycle('contains-marker=' + names.contains('compile-only-marker.jar')) - logger.lifecycle('contains-test-output=' + sourceSets.architectureTest.runtimeClasspath.files.containsAll(sourceSets.test.output.files)) - } - } - """); - - BuildResult result = runner("reportRuntime", "--console=plain").build(); - assertTrue(result.getOutput().contains("contains-marker=false"), result.getOutput()); - assertTrue(result.getOutput().contains("contains-test-output=true"), result.getOutput()); - } - - @Test - void defaultRuntimeKeepsVisibleOutputsWithoutLeakingCompileOnly() throws Exception { - Files.writeString(projectDir.resolve("compile-only-marker.jar"), "compile-only"); - Files.writeString(projectDir.resolve("runtime-only-marker.jar"), "runtime-only"); - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.auxiliary-source-set' - } - dependencies { - testCompileOnly files('compile-only-marker.jar') - testRuntimeOnly files('runtime-only-marker.jar') - } - auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' - inherits 'implementation', 'compileOnly', 'runtimeOnly' - } - } - tasks.register('reportRuntime') { - doLast { - def runtime = sourceSets.integrationTest.runtimeClasspath - def names = runtime.files*.name - logger.lifecycle('contains-compile-only=' + names.contains('compile-only-marker.jar')) - logger.lifecycle('contains-runtime-only=' + names.contains('runtime-only-marker.jar')) - logger.lifecycle('contains-main-output=' + runtime.files.containsAll(sourceSets.main.output.files)) - } - } - """); - BuildResult result = runner("reportRuntime", "--console=plain").build(); - assertTrue(result.getOutput().contains("contains-compile-only=false"), result.getOutput()); - assertTrue(result.getOutput().contains("contains-runtime-only=true"), result.getOutput()); - assertTrue(result.getOutput().contains("contains-main-output=true"), result.getOutput()); - } - - @Test - void unknownVisibleSourceSetFailsWithBothNames() throws Exception { - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.auxiliary-source-set' - } - auxiliarySourceSets { - sourceSet('performanceTest') { compilesAgainst 'main', 'missingKit' } - } - """); - - BuildResult result = runner("tasks").buildAndFail(); - assertTrue( - result.getOutput().contains("'performanceTest'") - && result.getOutput().contains("'missingKit'"), - result.getOutput()); - } - - private GradleRunner runner(String... args) { - return GradleRunner.create() - .withProjectDir(projectDir.toFile()) - .withPluginClasspath() - .withArguments(args); - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java index 73e28df9..ac1e0fd8 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java @@ -241,6 +241,46 @@ class StrictTestLaneConventionTest { assertTrue(result.getOutput().contains("contractLane"), result.getOutput()); } + @Test + void aLaneNamedAfterItsJvmTestSuiteMakesTheSuiteTaskStrict() throws Exception { + // given + buildFile( + """ + testing { + suites { + integrationTest(JvmTestSuite) { + useJUnitJupiter('5.11.3') + dependencies { implementation project() } + } + } + } + strictTestLanes { + lane('integrationTest') { + integration() + sourceSet = 'integrationTest' + description = 'The suite task under strict-lane rules.' + } + } + """); + Path suiteSource = projectDir.resolve("src/integrationTest/java"); + Files.createDirectories(suiteSource); + Files.writeString( + suiteSource.resolve("QuarantinedTest.java"), + """ + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + class QuarantinedTest { + @Test @Disabled("quarantined") void quarantined() {} + } + """); + + // when + BuildResult result = runner("integrationTest", "integrationTestLaneCheck").buildAndFail(); + + // then + assertTrue(result.getOutput().contains("a skip is not a result"), result.getOutput()); + } + @Test void laneSupportsTypedRuntimeAndOrderingOptions() throws Exception { Files.createDirectories(projectDir.resolve("contracts")); diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminActionUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminActionUseCaseConfiguration.java new file mode 100644 index 00000000..ccba7606 --- /dev/null +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminActionUseCaseConfiguration.java @@ -0,0 +1,95 @@ +package dev.caskeleton.composition.fileserver; + +import dev.caskeleton.application.fileserver.admin.AdminAudit; +import dev.caskeleton.application.fileserver.admin.AdminAuditPort; +import dev.caskeleton.application.fileserver.admin.CleanupUploadsApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.ForceDeleteFileApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.OrphanScanPort; +import dev.caskeleton.application.fileserver.admin.ReconcileOrphansApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.ReverifyFileApplicationUseCase; +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.CleanupQueuePort; +import dev.caskeleton.application.fileserver.cleanup.CleanupService; +import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint; +import dev.caskeleton.application.fileserver.port.in.CleanupUploadsUseCase; +import dev.caskeleton.application.fileserver.port.in.ForceDeleteFileUseCase; +import dev.caskeleton.application.fileserver.port.in.ReconcileOrphansUseCase; +import dev.caskeleton.application.fileserver.port.in.ReverifyFileUseCase; +import dev.caskeleton.application.fileserver.recovery.StagingUploadLocatorPort; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +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; + +/** + * The management plane's actions, on the admin switch, and the audit trail they write. + * + *

    Every operation here carries {@code file:admin}, and each one it takes is recorded. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "app.fileserver-platform.admin", + name = "enabled", + havingValue = "true") +class FileserverAdminActionUseCaseConfiguration { + + @Bean + @ConditionalOnMissingBean + AdminAudit fileserverAdminAuditTrail( + AdminAuditPort auditPort, SafeFileFingerprint fingerprint, Clock clock) { + return new AdminAudit(auditPort, fingerprint, clock); + } + + @Bean + @ConditionalOnMissingBean + ReconcileOrphansUseCase fileserverReconcileOrphans( + OrphanScanPort orphanScanPort, + CleanupQueuePort cleanupQueue, + FileAccessPolicyPort accessPolicy, + AdminAudit audit, + TransactionPort transactions) { + return new ReconcileOrphansApplicationUseCase( + orphanScanPort, cleanupQueue, accessPolicy, audit, transactions); + } + + @Bean + @ConditionalOnMissingBean + ReverifyFileUseCase fileserverReverifyFile( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + AdminAudit audit, + TransactionPort transactions) { + return new ReverifyFileApplicationUseCase(metadataStore, accessPolicy, audit, transactions); + } + + @Bean + @ConditionalOnMissingBean + ForceDeleteFileUseCase fileserverForceDeleteFile( + FileMetadataPort metadataStore, + UploadSessionPort sessionStore, + StagingUploadLocatorPort stagingLocator, + CleanupQueuePort cleanupQueue, + FileAccessPolicyPort accessPolicy, + AdminAudit audit, + TransactionPort transactions) { + return new ForceDeleteFileApplicationUseCase( + metadataStore, + sessionStore, + stagingLocator, + cleanupQueue, + accessPolicy, + audit, + transactions); + } + + @Bean + @ConditionalOnMissingBean + CleanupUploadsUseCase fileserverCleanupUploads( + CleanupService cleanupService, FileAccessPolicyPort accessPolicy, AdminAudit audit) { + return new CleanupUploadsApplicationUseCase(cleanupService, accessPolicy, audit); + } +} diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminReadUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminReadUseCaseConfiguration.java new file mode 100644 index 00000000..d01e8d73 --- /dev/null +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverAdminReadUseCaseConfiguration.java @@ -0,0 +1,66 @@ +package dev.caskeleton.composition.fileserver; + +import dev.caskeleton.application.fileserver.admin.GetRuntimeCapabilitiesApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.GetStorageHealthApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.ListIncompleteUploadsApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.ListOrphansApplicationUseCase; +import dev.caskeleton.application.fileserver.admin.OrphanScanPort; +import dev.caskeleton.application.fileserver.admin.StorageHealthPort; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.api.security.FileAccessPolicyPort; +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.transaction.TransactionPort; +import java.time.Clock; +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; + +/** + * The management plane's reads, on the admin switch. + * + *

    Admin is a separate decision from the data plane: a deployment that serves files does not + * automatically want an operator surface. Every operation here carries {@code file:admin}. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "app.fileserver-platform.admin", + name = "enabled", + havingValue = "true") +class FileserverAdminReadUseCaseConfiguration { + + @Bean + @ConditionalOnMissingBean + GetStorageHealthUseCase fileserverGetStorageHealth( + StorageHealthPort healthPort, FileAccessPolicyPort accessPolicy) { + return new GetStorageHealthApplicationUseCase(healthPort, accessPolicy); + } + + @Bean + @ConditionalOnMissingBean + GetRuntimeCapabilitiesUseCase fileserverGetRuntimeCapabilities( + StorageHealthPort healthPort, FileAccessPolicyPort accessPolicy) { + return new GetRuntimeCapabilitiesApplicationUseCase(healthPort, accessPolicy); + } + + @Bean + @ConditionalOnMissingBean + ListOrphansUseCase fileserverListOrphans( + OrphanScanPort orphanScanPort, FileAccessPolicyPort accessPolicy) { + return new ListOrphansApplicationUseCase(orphanScanPort, accessPolicy); + } + + @Bean + @ConditionalOnMissingBean + ListIncompleteUploadsUseCase fileserverListIncompleteUploads( + UploadSessionPort sessionStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions, + Clock clock) { + return new ListIncompleteUploadsApplicationUseCase( + sessionStore, accessPolicy, transactions, clock); + } +} diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java new file mode 100644 index 00000000..37a2e54a --- /dev/null +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverFileUseCaseConfiguration.java @@ -0,0 +1,120 @@ +package dev.caskeleton.composition.fileserver; + +import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverMetricsSupport; +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.DescribeFileApplicationUseCase; +import dev.caskeleton.application.fileserver.download.DownloadContentPort; +import dev.caskeleton.application.fileserver.download.OpenDownloadContentApplicationUseCase; +import dev.caskeleton.application.fileserver.download.PrepareDownloadApplicationUseCase; +import dev.caskeleton.application.fileserver.download.TransferDownloadContentApplicationUseCase; +import dev.caskeleton.application.fileserver.download.ZeroCopyDownloadPort; +import dev.caskeleton.application.fileserver.lifecycle.CopyContentPort; +import dev.caskeleton.application.fileserver.lifecycle.CopyFileApplicationUseCase; +import dev.caskeleton.application.fileserver.lifecycle.DeleteFileApplicationUseCase; +import dev.caskeleton.application.fileserver.lifecycle.MoveFileApplicationUseCase; +import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; +import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase; +import dev.caskeleton.application.fileserver.port.in.DeleteFileUseCase; +import dev.caskeleton.application.fileserver.port.in.DescribeFileUseCase; +import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase; +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.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; + +/** + * The operations on a stored file: describe, download, delete, copy, move. + * + *

    The reads carry no permission, because a deployment may allow anonymous reads and only {@code + * FileAccessPolicyPort} can decide that; the writes carry {@code file:delete}, {@code file:copy} + * and {@code file:move}, enforced on the bean's proxy. + */ +@Configuration(proxyBeanMethods = false) +class FileserverFileUseCaseConfiguration { + + @Bean + @ConditionalOnMissingBean + DescribeFileUseCase fileserverDescribeFile( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions) { + return new DescribeFileApplicationUseCase(metadataStore, accessPolicy, transactions); + } + + @Bean + @ConditionalOnMissingBean + PrepareDownloadUseCase fileserverPrepareDownload( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions) { + return new PrepareDownloadApplicationUseCase(metadataStore, accessPolicy, transactions); + } + + @Bean + @ConditionalOnMissingBean + OpenDownloadContentUseCase fileserverOpenDownloadContent(DownloadContentPort contentGateway) { + return new OpenDownloadContentApplicationUseCase(contentGateway); + } + + @Bean + @ConditionalOnMissingBean + TransferDownloadContentUseCase fileserverTransferDownloadContent( + ZeroCopyDownloadPort zeroCopyGateway, ObjectProvider metrics) { + return new TransferDownloadContentApplicationUseCase( + Optional.of(zeroCopyGateway), FileserverMetricsSupport.metricsOrNoop(metrics)); + } + + @Bean + @ConditionalOnMissingBean + DeleteFileUseCase fileserverDeleteFile( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + CleanupQueuePort cleanupQueue, + UploadSessionPort sessionStore, + StagingUploadLocatorPort stagingLocator, + TransactionPort transactions) { + return new DeleteFileApplicationUseCase( + metadataStore, accessPolicy, cleanupQueue, sessionStore, stagingLocator, transactions); + } + + @Bean + @ConditionalOnMissingBean + CopyFileUseCase fileserverCopyFile( + FileMetadataPort metadataStore, + CopyContentPort copyGateway, + FileAccessPolicyPort accessPolicy, + OriginalFilenamePolicy filenamePolicy, + UploadIdentifierPort identifierFactory, + TransactionPort transactions, + Clock clock) { + return new CopyFileApplicationUseCase( + metadataStore, + copyGateway, + accessPolicy, + filenamePolicy, + identifierFactory, + transactions, + clock); + } + + @Bean + @ConditionalOnMissingBean + MoveFileUseCase fileserverMoveFile( + FileMetadataPort metadataStore, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions) { + return new MoveFileApplicationUseCase(metadataStore, accessPolicy, transactions); + } +} diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java index 9f31ea18..e9060f45 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java @@ -40,7 +40,11 @@ import org.springframework.context.annotation.Import; // the composition root's job by definition, so these are where they belong rather than where // they were left. FileserverLocalStorageCoreConfiguration.class, - FileserverUploadServiceConfiguration.class, + FileserverUploadSupportConfiguration.class, + FileserverUploadUseCaseConfiguration.class, + FileserverFileUseCaseConfiguration.class, + FileserverAdminReadUseCaseConfiguration.class, + FileserverAdminActionUseCaseConfiguration.class, FileserverCleanupConfiguration.class, // The HTTP surface itself. Its controllers used to be found by the composition root's component // scan of `dev.caskeleton.adapter`; the capability now brings them, so selecting it is enough. diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadSupportConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadSupportConfiguration.java new file mode 100644 index 00000000..4d557dc9 --- /dev/null +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadSupportConfiguration.java @@ -0,0 +1,63 @@ +package dev.caskeleton.composition.fileserver; + +import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings; +import dev.caskeleton.adapter.outbound.fileserver.platform.identifier.RandomUploadIdentifier; +import dev.caskeleton.application.fileserver.api.metadata.UploadSessionPort; +import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; +import dev.caskeleton.application.fileserver.quota.StorageUsagePort; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; +import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties; +import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; +import dev.caskeleton.application.fileserver.upload.UploadPolicy; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * What every upload use case stands on: the identifier generator, transfer admission and the writer + * lease. The use cases themselves are {@link FileserverUploadUseCaseConfiguration}'s. + */ +@Configuration(proxyBeanMethods = false) +class FileserverUploadSupportConfiguration { + + @Bean + @ConditionalOnMissingBean + UploadIdentifierPort fileserverIdentifierFactory() { + return new RandomUploadIdentifier(); + } + + @Bean + @ConditionalOnMissingBean + TransferAdmissionProperties fileserverAdmissionProperties(FileserverPlatformSettings settings) { + FileserverPlatformSettings.Quota quota = settings.quota(); + return new TransferAdmissionProperties( + quota.instanceUploadPermits(), + quota.scopeUploadPermits(), + quota.directDownloadPermits(), + quota.softHighWater(), + quota.hardHighWater()); + } + + @Bean + @ConditionalOnMissingBean + TransferAdmissionController fileserverAdmissionController( + TransferAdmissionProperties properties, + StorageUsagePort usageProbe, + FileserverPlatformSettings settings) { + return new TransferAdmissionController( + properties, usageProbe, settings.upload().maxFileSize().toBytes()); + } + + @Bean + @ConditionalOnMissingBean + WriterLeaseCoordinator fileserverWriterLeaseCoordinator( + UploadSessionPort sessionStore, + UploadPolicy uploadPolicy, + TransactionPort transactions, + Clock clock) { + return new WriterLeaseCoordinator( + sessionStore, uploadPolicy.leaseDuration(), transactions, clock); + } +} diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java similarity index 51% rename from src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java rename to src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java index 99386dc4..b3ad559e 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadUseCaseConfiguration.java @@ -1,8 +1,6 @@ package dev.caskeleton.composition.fileserver; import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverMetricsSupport; -import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings; -import dev.caskeleton.adapter.outbound.fileserver.platform.identifier.RandomUploadIdentifierFactory; import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore; import dev.caskeleton.application.fileserver.api.metadata.FileMetadataPort; import dev.caskeleton.application.fileserver.api.metadata.FileQuotaPort; @@ -12,19 +10,23 @@ import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy import dev.caskeleton.application.fileserver.cleanup.CleanupQueuePort; import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort; -import dev.caskeleton.application.fileserver.quota.StorageUsagePort; +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.FinalizeUploadUseCase; +import dev.caskeleton.application.fileserver.port.in.GetUploadStatusUseCase; +import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase; import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; -import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties; import dev.caskeleton.application.fileserver.recovery.RecoveryQueuePort; -import dev.caskeleton.application.fileserver.upload.DefaultFinalizeUploadService; -import dev.caskeleton.application.fileserver.upload.DefaultSingleShotUploadService; -import dev.caskeleton.application.fileserver.upload.DefaultUploadApplicationService; +import dev.caskeleton.application.fileserver.upload.AppendUploadApplicationUseCase; +import dev.caskeleton.application.fileserver.upload.CancelUploadApplicationUseCase; +import dev.caskeleton.application.fileserver.upload.CreateUploadApplicationUseCase; import dev.caskeleton.application.fileserver.upload.FileVerificationPort; -import dev.caskeleton.application.fileserver.upload.FinalizeUploadService; +import dev.caskeleton.application.fileserver.upload.FinalizeUploadApplicationUseCase; +import dev.caskeleton.application.fileserver.upload.GetUploadStatusApplicationUseCase; import dev.caskeleton.application.fileserver.upload.QuotaCommitPort; -import dev.caskeleton.application.fileserver.upload.SingleShotUploadService; -import dev.caskeleton.application.fileserver.upload.UploadApplicationService; import dev.caskeleton.application.fileserver.upload.UploadContentPort; +import dev.caskeleton.application.fileserver.upload.UploadFileApplicationUseCase; import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; import dev.caskeleton.application.fileserver.upload.UploadPolicies; import dev.caskeleton.application.fileserver.upload.UploadPolicy; @@ -37,62 +39,73 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +/** + * The upload operations, one bean each. + * + *

    Each is a use case with its own declared capability; the writes also carry a {@code + * file:upload} permission, which the web adapter's method security enforces on the bean's proxy. + * That is why they are container beans rather than objects a controller builds: an instance made + * with {@code new} outside the container is never proxied, and its permission would be a comment. + * Roles and ownership are still {@code FileAccessPolicyPort}'s, inside each use case. + */ @Configuration(proxyBeanMethods = false) -class FileserverUploadServiceConfiguration { +class FileserverUploadUseCaseConfiguration { @Bean @ConditionalOnMissingBean - UploadIdentifierPort fileserverIdentifierFactory() { - return new RandomUploadIdentifierFactory(); + UploadStores fileserverUploadStores( + FileMetadataPort metadataStore, UploadSessionPort sessionStore, CleanupQueuePort queue) { + return new UploadStores(metadataStore, sessionStore, queue); } @Bean @ConditionalOnMissingBean - TransferAdmissionProperties fileserverAdmissionProperties(FileserverPlatformSettings settings) { - FileserverPlatformSettings.Quota quota = settings.quota(); - return new TransferAdmissionProperties( - quota.instanceUploadPermits(), - quota.scopeUploadPermits(), - quota.directDownloadPermits(), - quota.softHighWater(), - quota.hardHighWater()); + UploadPolicies fileserverUploadPolicies( + FileAccessPolicyPort accessPolicy, + OriginalFilenamePolicy filenamePolicy, + UploadPolicy uploadPolicy) { + return new UploadPolicies(accessPolicy, filenamePolicy, uploadPolicy); } @Bean @ConditionalOnMissingBean - TransferAdmissionController fileserverAdmissionController( - TransferAdmissionProperties properties, - StorageUsagePort usageProbe, - FileserverPlatformSettings settings) { - return new TransferAdmissionController( - properties, usageProbe, settings.upload().maxFileSize().toBytes()); - } - - @Bean - @ConditionalOnMissingBean - UploadApplicationService fileserverUploadService( - FileMetadataPort metadataStore, - UploadSessionPort sessionStore, - WriterLeaseCoordinator leaseCoordinator, + CreateUploadUseCase fileserverCreateUpload( + UploadStores stores, + UploadPolicies policies, UploadStoragePort storageGateway, FileQuotaPort quotaService, TransferAdmissionController admissionController, - FileAccessPolicyPort accessPolicy, - OriginalFilenamePolicy filenamePolicy, - CleanupQueuePort cleanupQueue, UploadIdentifierPort identifierFactory, - UploadPolicy uploadPolicy, - ObjectProvider metrics, TransactionPort transactions, Clock clock) { - return new DefaultUploadApplicationService( - new UploadStores(metadataStore, sessionStore, cleanupQueue), - new UploadPolicies(accessPolicy, filenamePolicy, uploadPolicy), - leaseCoordinator, + return new CreateUploadApplicationUseCase( + stores, + policies, storageGateway, quotaService, admissionController, identifierFactory, + transactions, + clock); + } + + @Bean + @ConditionalOnMissingBean + AppendUploadUseCase fileserverAppendUpload( + UploadStores stores, + UploadPolicies policies, + WriterLeaseCoordinator leaseCoordinator, + UploadStoragePort storageGateway, + TransferAdmissionController admissionController, + ObjectProvider metrics, + TransactionPort transactions, + Clock clock) { + return new AppendUploadApplicationUseCase( + stores, + policies, + leaseCoordinator, + storageGateway, + admissionController, FileserverMetricsSupport.metricsOrNoop(metrics), transactions, clock); @@ -100,7 +113,24 @@ class FileserverUploadServiceConfiguration { @Bean @ConditionalOnMissingBean - FinalizeUploadService fileserverFinalizeService( + GetUploadStatusUseCase fileserverGetUploadStatus( + UploadStores stores, + FileAccessPolicyPort accessPolicy, + TransactionPort transactions, + Clock clock) { + return new GetUploadStatusApplicationUseCase(stores, accessPolicy, transactions, clock); + } + + @Bean + @ConditionalOnMissingBean + CancelUploadUseCase fileserverCancelUpload( + UploadStores stores, FileAccessPolicyPort accessPolicy, TransactionPort transactions) { + return new CancelUploadApplicationUseCase(stores, accessPolicy, transactions); + } + + @Bean + @ConditionalOnMissingBean + FinalizeUploadUseCase fileserverFinalizeUpload( FileMetadataPort metadataStore, UploadSessionPort sessionStore, UploadContentPort contentGateway, @@ -112,7 +142,7 @@ class FileserverUploadServiceConfiguration { LocalBlockingContentStore store, TransactionPort transactions, Clock clock) { - return new DefaultFinalizeUploadService( + return new FinalizeUploadApplicationUseCase( metadataStore, sessionStore, contentGateway, @@ -126,21 +156,19 @@ class FileserverUploadServiceConfiguration { clock); } + /** + * The single-request upload, over the other upload use cases' beans. + * + *

    It takes the proxies, not new instances, so each step it composes is authorized exactly as + * it would be when a client called it directly. + */ @Bean @ConditionalOnMissingBean - SingleShotUploadService fileserverSingleShotUploadService( - UploadApplicationService uploadService, FinalizeUploadService finalizeService) { - return new DefaultSingleShotUploadService(uploadService, finalizeService); - } - - @Bean - @ConditionalOnMissingBean - WriterLeaseCoordinator fileserverWriterLeaseCoordinator( - UploadSessionPort sessionStore, - UploadPolicy uploadPolicy, - TransactionPort transactions, - Clock clock) { - return new WriterLeaseCoordinator( - sessionStore, uploadPolicy.leaseDuration(), transactions, clock); + UploadFileUseCase fileserverUploadFile( + CreateUploadUseCase create, + AppendUploadUseCase append, + FinalizeUploadUseCase finalizer, + CancelUploadUseCase cancel) { + return new UploadFileApplicationUseCase(create, append, finalizer, cancel); } } diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java index 3dd0bc15..b23742fc 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverRuntimeAssemblyTest.java @@ -6,27 +6,42 @@ import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.Fileser import dev.caskeleton.adapter.outbound.fileserver.platform.security.RoleBasedFileAccessPolicy; import dev.caskeleton.adapter.outbound.fileserver.platform.security.UnenforcedFileAccessPolicy; import dev.caskeleton.application.fileserver.admin.AdminAuditPort; -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.security.FileAccessPolicyPort; import dev.caskeleton.application.fileserver.cleanup.CleanupContentPort; import dev.caskeleton.application.fileserver.cleanup.CleanupService; import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator; -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.FileLifecycleService; import dev.caskeleton.application.fileserver.observability.FileserverAuditPort; +import dev.caskeleton.application.fileserver.port.in.AppendUploadUseCase; +import dev.caskeleton.application.fileserver.port.in.CancelUploadUseCase; +import dev.caskeleton.application.fileserver.port.in.CleanupUploadsUseCase; +import dev.caskeleton.application.fileserver.port.in.CopyFileUseCase; +import dev.caskeleton.application.fileserver.port.in.CreateUploadUseCase; +import dev.caskeleton.application.fileserver.port.in.DeleteFileUseCase; +import dev.caskeleton.application.fileserver.port.in.DescribeFileUseCase; +import dev.caskeleton.application.fileserver.port.in.FinalizeUploadUseCase; +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.GetUploadStatusUseCase; +import dev.caskeleton.application.fileserver.port.in.ListIncompleteUploadsUseCase; +import dev.caskeleton.application.fileserver.port.in.ListOrphansUseCase; +import dev.caskeleton.application.fileserver.port.in.MoveFileUseCase; +import dev.caskeleton.application.fileserver.port.in.OpenDownloadContentUseCase; +import dev.caskeleton.application.fileserver.port.in.PrepareDownloadUseCase; +import dev.caskeleton.application.fileserver.port.in.ReconcileOrphansUseCase; +import dev.caskeleton.application.fileserver.port.in.ReverifyFileUseCase; +import dev.caskeleton.application.fileserver.port.in.TransferDownloadContentUseCase; +import dev.caskeleton.application.fileserver.port.in.UploadFileUseCase; import dev.caskeleton.application.fileserver.quota.StorageUsagePort; import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; import dev.caskeleton.application.fileserver.recovery.FileReconciliationService; import dev.caskeleton.application.fileserver.recovery.ReconciliationContentPort; import dev.caskeleton.application.fileserver.upload.FileVerificationPort; -import dev.caskeleton.application.fileserver.upload.FinalizeUploadService; -import dev.caskeleton.application.fileserver.upload.SingleShotUploadService; -import dev.caskeleton.application.fileserver.upload.UploadApplicationService; import dev.caskeleton.application.fileserver.upload.UploadContentPort; import dev.caskeleton.application.fileserver.upload.UploadIdentifierPort; import dev.caskeleton.application.fileserver.upload.UploadStoragePort; @@ -88,11 +103,19 @@ class FileserverRuntimeAssemblyTest { .forEach(port -> assertThat(context).hasSingleBean(port)); List.of( - UploadApplicationService.class, - FinalizeUploadService.class, - SingleShotUploadService.class, - DownloadApplicationService.class, - FileLifecycleService.class, + CreateUploadUseCase.class, + AppendUploadUseCase.class, + GetUploadStatusUseCase.class, + CancelUploadUseCase.class, + FinalizeUploadUseCase.class, + UploadFileUseCase.class, + DescribeFileUseCase.class, + PrepareDownloadUseCase.class, + OpenDownloadContentUseCase.class, + TransferDownloadContentUseCase.class, + DeleteFileUseCase.class, + CopyFileUseCase.class, + MoveFileUseCase.class, CleanupService.class, FileReconciliationService.class, WriterLeaseCoordinator.class, @@ -105,7 +128,16 @@ class FileserverRuntimeAssemblyTest { assertThat(context).hasSingleBean(FileserverAuditPort.class); assertThat(context.getBean(FileAccessPolicyPort.class)) .isInstanceOf(RoleBasedFileAccessPolicy.class); - assertThat(context).doesNotHaveBean(FileserverAdminService.class); + List.of( + GetStorageHealthUseCase.class, + GetRuntimeCapabilitiesUseCase.class, + ListOrphansUseCase.class, + ReconcileOrphansUseCase.class, + ReverifyFileUseCase.class, + ForceDeleteFileUseCase.class, + ListIncompleteUploadsUseCase.class, + CleanupUploadsUseCase.class) + .forEach(operation -> assertThat(context).doesNotHaveBean(operation)); assertThat(context).doesNotHaveBean(FileserverCleanupWorker.class); }); } @@ -153,7 +185,18 @@ class FileserverRuntimeAssemblyTest { void theAdminPlaneAppearsOnItsOwnSwitch() { enabled() .withPropertyValues("app.fileserver-platform.admin.enabled=true") - .run(context -> assertThat(context).hasSingleBean(FileserverAdminService.class)); + .run( + context -> + List.of( + GetStorageHealthUseCase.class, + GetRuntimeCapabilitiesUseCase.class, + ListOrphansUseCase.class, + ReconcileOrphansUseCase.class, + ReverifyFileUseCase.class, + ForceDeleteFileUseCase.class, + ListIncompleteUploadsUseCase.class, + CleanupUploadsUseCase.class) + .forEach(operation -> assertThat(context).hasSingleBean(operation))); } @Test diff --git a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java index e0fc7a28..8ec4b8ca 100644 --- a/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java +++ b/src/composition/idempotency/src/test/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfigurationTest.java @@ -74,7 +74,7 @@ class IdempotencyAutoConfigurationTest { .hasSingleBean(IdempotencyExecutor.class) .getBean(IdempotencyStorePort.class) .extracting(store -> store.getClass().getSimpleName()) - .isEqualTo("PostgreSqlOwnerSafeIdempotencyStore")); + .isEqualTo("PostgreSqlIdempotencyStore")); } @Test diff --git a/src/grpc/grpc-operation-ledger-jpa/build.gradle b/src/grpc/grpc-operation-ledger-jpa/build.gradle index d9796995..9ecb4dda 100644 --- a/src/grpc/grpc-operation-ledger-jpa/build.gradle +++ b/src/grpc/grpc-operation-ledger-jpa/build.gradle @@ -1,13 +1,20 @@ plugins { - id 'ca.auxiliary-source-set' id 'ca.platform-module' } -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' +testing { + suites { + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + } + } } } +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} // Durable mutation idempotency: the operation ledger entity, its state machine, the vendor-neutral // repository port and the Spring Data JPA binding, plus the migration that owns the unique diff --git a/src/messaging/messaging-kafka/build.gradle b/src/messaging/messaging-kafka/build.gradle index 8f28164f..00c9892e 100644 --- a/src/messaging/messaging-kafka/build.gradle +++ b/src/messaging/messaging-kafka/build.gradle @@ -1,6 +1,5 @@ plugins { id 'java-test-fixtures' - id 'ca.auxiliary-source-set' id 'ca.platform-module' id 'me.champeau.jmh' } @@ -10,11 +9,20 @@ jmh { includeTests = true } -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main', 'testFixtures' +testing { + suites { + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project()) + } + } } } +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} dependencies { // No spring-kafka. It was declared here and imported by nothing: this adapter drives the plain diff --git a/src/messaging/messaging-reliability-jdbc-postgresql/build.gradle b/src/messaging/messaging-reliability-jdbc-postgresql/build.gradle index cfa5217b..f549b2d0 100644 --- a/src/messaging/messaging-reliability-jdbc-postgresql/build.gradle +++ b/src/messaging/messaging-reliability-jdbc-postgresql/build.gradle @@ -1,13 +1,20 @@ plugins { - id 'ca.auxiliary-source-set' id 'ca.platform-module' } -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' +testing { + suites { + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + } + } } } +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} // The relational implementations of the reliability ports: the outbox repository, the inbox // repository and the destructive-operation journal. Spring JDBC for the transaction join, and SQL diff --git a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java index f3f1d2a7..16becff1 100644 --- a/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java +++ b/src/messaging/messaging-reliability-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java @@ -290,14 +290,31 @@ class OutboxPostgresIT { if (directory == null) { throw new IOException("the messaging migrations are missing from the classpath"); } - java.io.File[] files = - new java.io.File(java.net.URI.create(directory.toString())) - .listFiles((dir, name) -> name.endsWith(".sql")); - if (files == null || files.length == 0) { + // The migrations may sit in a directory or, when the suite runs against the main jar, inside + // it; a jar URL is not a file URI, so list through a filesystem that understands either. + java.net.URI uri; + try { + uri = directory.toURI(); + } catch (java.net.URISyntaxException malformed) { + throw new IOException(malformed); + } + java.util.List names; + if ("jar".equals(uri.getScheme())) { + try (java.nio.file.FileSystem jar = + java.nio.file.FileSystems.newFileSystem(uri, java.util.Map.of()); + java.util.stream.Stream listed = + java.nio.file.Files.list(jar.getPath("db/migration/messaging"))) { + names = sqlNames(listed); + } + } else { + try (java.util.stream.Stream listed = + java.nio.file.Files.list(java.nio.file.Path.of(uri))) { + names = sqlNames(listed); + } + } + if (names.isEmpty()) { throw new IOException("no migration applied; the schema under test would be empty"); } - java.util.List names = - java.util.Arrays.stream(files).map(java.io.File::getName).sorted().toList(); java.util.List statements = new java.util.ArrayList<>(); for (String name : names) { statements.add(migration(name)); @@ -305,6 +322,15 @@ class OutboxPostgresIT { return statements; } + private static java.util.List sqlNames( + java.util.stream.Stream listed) { + return listed + .map(path -> path.getFileName().toString()) + .filter(name -> name.endsWith(".sql")) + .sorted() + .toList(); + } + private int countWhere(String predicate) { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); diff --git a/src/messaging/messaging-spring-boot-starter/build.gradle b/src/messaging/messaging-spring-boot-starter/build.gradle index 7f3f7811..efed4b94 100644 --- a/src/messaging/messaging-spring-boot-starter/build.gradle +++ b/src/messaging/messaging-spring-boot-starter/build.gradle @@ -1,5 +1,4 @@ plugins { - id 'ca.auxiliary-source-set' id 'ca.platform-module' id 'ca.spring-config' } @@ -9,11 +8,19 @@ plugins { // `api` is the types that genuinely appear in this module's public signatures; everything else is // `implementation`. Broker transports live in capability starters (messaging-spring-boot-starter-kafka), // so this starter's compile classpath carries no broker SDK. -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main' +testing { + suites { + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + } + } } } +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly +} dependencies { // Types an adopter writes against: envelopes, destinations, publish results, profiles, ports. diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index d93b6f37..5450064f 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -2,7 +2,6 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' id 'org.springframework.boot' - id 'ca.auxiliary-source-set' id 'java-test-fixtures' } @@ -22,17 +21,36 @@ tasks.named('test') { .withPathSensitivity(PathSensitivity.RELATIVE) } -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main', 'testFixtures' - } - sourceSet('systemTest') { - compilesAgainst 'main', 'testFixtures' - } - sourceSet('webSystemTest') { - compilesAgainst 'main', 'testFixtures' +testing { + suites { + integrationTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project()) + } + } + systemTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project()) + } + } + webSystemTest(JvmTestSuite) { + dependencies { + implementation project() + implementation testFixtures(project()) + } + } } } +configurations { + integrationTestImplementation.extendsFrom testImplementation + integrationTestRuntimeOnly.extendsFrom testRuntimeOnly + systemTestImplementation.extendsFrom testImplementation + systemTestRuntimeOnly.extendsFrom testRuntimeOnly + webSystemTestImplementation.extendsFrom testImplementation + webSystemTestRuntimeOnly.extendsFrom testRuntimeOnly +} // The objectstorage adapter (runtimeOnly) pulls in software.amazon.awssdk:s3, whose version is // managed by the AWS SDK v2 BOM (NOT the Spring Boot BOM). Import that BOM at this consumer's scope diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java index 580932b1..b9fa6679 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventContracts.java @@ -19,13 +19,6 @@ public final class PortfolioEventContracts { PosterCreatedPayload.class, "8be3a72b7b469d894d06bd30f79f565feb23fbf698674d5caee094de5a2300fb"); - public static final PortfolioEventContract POSTER_IMAGE_ATTACHED = - PortfolioEventContract.of( - "poster.image-attached", - 1, - PosterImageAttachedPayload.class, - "8021e7676928d8cb0fd29edf052be8d37fb5e87284c3eb4b947942d395aedd99"); - public static final PortfolioEventContract POSTER_PUBLISHED = PortfolioEventContract.of( "poster.published", @@ -69,7 +62,6 @@ public final class PortfolioEventContracts { public static List> all() { return List.of( POSTER_CREATED, - POSTER_IMAGE_ATTACHED, POSTER_PUBLISHED, POSTER_ARCHIVED, POSTER_DELETED, diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java index d4cc5bb1..0757f521 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisher.java @@ -3,7 +3,6 @@ package dev.caskeleton.sample.portfolio.application.event; import dev.caskeleton.sample.portfolio.domain.poster.PosterArchived; import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated; import dev.caskeleton.sample.portfolio.domain.poster.PosterDeleted; -import dev.caskeleton.sample.portfolio.domain.poster.PosterImageAttached; import dev.caskeleton.sample.portfolio.domain.poster.PosterPublished; /** @@ -31,15 +30,6 @@ public class PosterEventPublisher { new PosterCreatedPayload(posterId, e.title())); } - public void publishImageAttached(PosterImageAttached e) { - String posterId = e.posterId().value(); - outbox.append( - PortfolioEventContracts.POSTER_IMAGE_ATTACHED, - AGGREGATE_TYPE, - posterId, - new PosterImageAttachedPayload(posterId, e.imageKey())); - } - public void publishPublished(PosterPublished e) { publishIdOnly(PortfolioEventContracts.POSTER_PUBLISHED, e.posterId().value()); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java deleted file mode 100644 index c2b572eb..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachedPayload.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.event; - -import dev.caskeleton.application.messaging.contract.IntegrationPayload; - -/** - * Payload of {@code poster.image-attached} v1, the legacy direct upload's announcement. - * - * @param posterId the poster - * @param imageKey the stored object's key - */ -public record PosterImageAttachedPayload(String posterId, String imageKey) - implements IntegrationPayload {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java index a54e7719..1b9233b1 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyPayload.java @@ -4,8 +4,8 @@ import dev.caskeleton.application.messaging.contract.IntegrationPayload; /** * Payload of {@code poster.image-attachment-ready} v2: the published image reference. Version 2 - * because {@code poster.image-attached} v1, which carried the raw object key, came first and still - * exists for the legacy upload. + * because {@code poster.image-attached} v1, which carried the raw object key, came first; that event + * left with the legacy upload, and the version number stays so no consumer sees it reused. * * @param posterId the poster * @param operationId the upload operation diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java index b492d1b4..60644bdd 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/application/SampleApplicationUseCaseConfig.java @@ -10,7 +10,6 @@ import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox; import dev.caskeleton.sample.portfolio.application.event.PosterCreatedPayload; import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher; import dev.caskeleton.sample.portfolio.application.event.PosterIdPayload; -import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachedPayload; import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentPreparedPayload; import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentReadyPayload; import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; @@ -62,11 +61,6 @@ public class SampleApplicationUseCaseConfig { return PortfolioEventContracts.POSTER_CREATED; } - @Bean - PortfolioEventContract posterImageAttachedContract() { - return PortfolioEventContracts.POSTER_IMAGE_ATTACHED; - } - @Bean PortfolioEventContract posterPublishedContract() { return PortfolioEventContracts.POSTER_PUBLISHED; diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttached.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttached.java deleted file mode 100644 index d4a4c012..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttached.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.sample.portfolio.domain.poster; - -import dev.caskeleton.domain.stereotype.DomainEvent; -import java.util.Objects; - -/** - * Domain event: an image was attached to a {@link Poster}. Transport-free; carries domain data - * only. - */ -@DomainEvent -public record PosterImageAttached(PosterId posterId, String imageKey) { - - public PosterImageAttached { - Objects.requireNonNull(posterId, "posterId is required"); - Objects.requireNonNull(imageKey, "imageKey is required"); - } -} diff --git a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json b/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json deleted file mode 100644 index d315308d..00000000 --- a/src/sample-portfolio/src/main/resources/contracts/messaging/poster.image-attached/v1.schema.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attached:v1", - "title": "PosterImageAttached payload v1", - "type": "object", - "required": [ - "posterId", - "imageKey" - ], - "properties": { - "posterId": { - "type": "string", - "minLength": 1, - "maxLength": 160, - "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" - }, - "imageKey": { - "type": "string", - "minLength": 1 - } - }, - "unevaluatedProperties": false -}