From 42d84d505e975ca7282b0bca1bdf4f7990fb2312 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 07:10:55 +0900 Subject: [PATCH 1/5] =?UTF-8?q?fix(objectstorage):=20=EB=B6=88=EB=B3=80=20?= =?UTF-8?q?Set=EC=9C=BC=EB=A1=9C=20=EB=A7=8C=EB=93=A0=20=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=EC=97=90=EC=84=9C=20NPE=EB=A5=BC=20=EB=82=B4=EC=A7=80=20?= =?UTF-8?q?=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: ObjectRequestSupport.immutableCapabilities가 null 원소를 거르려고 capabilities.contains(null)을 불렀다. JDK의 불변 Set(Set.of, Set.copyOf)은 contains(null)에서 false 대신 NullPointerException을 던진다. 그래서 게시·stage 요청을 Set.of(...) capability로 만들면 생성자가 NPE로 실패했다. 지금 호출자가 모두 EnumSet을 넘겨 드러나지 않았고, 포트 계약 시험(다음 커밋)이 처음 잡았다. 고친 것: 원소를 하나씩 보고 null이면 지금처럼 IllegalArgumentException을 던진다. 검증: desktop, 기준 4ca61cd9에 새 시험만 → 「불변 Set으로 만든 요청」이 NPE로 실패. 고친 뒤 :application-objectstorage:check 통과(다음 커밋의 GREEN 실행에 포함). Refs: RR9-03-33 --- .../request/ObjectRequestSupport.java | 8 +- .../ObjectRequestCapabilitiesTest.java | 77 +++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/request/ObjectRequestCapabilitiesTest.java diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java index 2a25b28e..02b02c77 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java @@ -18,8 +18,12 @@ final class ObjectRequestSupport { static Set immutableCapabilities( Set capabilities) { required(capabilities, "capabilities"); - if (capabilities.contains(null)) { - throw new IllegalArgumentException("capabilities must not contain null"); + // Each element, not contains(null): an immutable Set (Set.of, Set.copyOf) throws + // NullPointerException from contains(null) instead of answering false. + for (ObjectCapabilityRequirement capability : capabilities) { + if (capability == null) { + throw new IllegalArgumentException("capabilities must not contain null"); + } } return Set.copyOf(capabilities); } diff --git a/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/request/ObjectRequestCapabilitiesTest.java b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/request/ObjectRequestCapabilitiesTest.java new file mode 100644 index 00000000..5ee9fbbb --- /dev/null +++ b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/request/ObjectRequestCapabilitiesTest.java @@ -0,0 +1,77 @@ +package dev.caskeleton.application.objectstorage.request; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.objectstorage.content.CallBudget; +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; +import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.application.objectstorage.model.ObjectEncryptionRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectMediaType; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; +import java.time.Duration; +import java.util.HashSet; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** The capability set a publish or stage request carries. */ +class ObjectRequestCapabilitiesTest { + + @Test + @DisplayName("불변 Set으로 만든 요청도 그 capability를 그대로 담는다") + void anImmutableCapabilitySetIsAccepted() { + // given + Set capabilities = + Set.of(ObjectCapabilityRequirement.IMMUTABLE_CREATE); + + // when + ObjectPublishRequest request = publishRequest(capabilities); + + // then + assertThat(request.capabilityRequirements()) + .containsExactly(ObjectCapabilityRequirement.IMMUTABLE_CREATE); + } + + @Test + @DisplayName("null을 담은 capability Set은 거절한다") + void aCapabilitySetHoldingNullIsRefused() { + // given + Set capabilities = new HashSet<>(); + capabilities.add(ObjectCapabilityRequirement.IMMUTABLE_CREATE); + capabilities.add(null); + + // when + Throwable refused = catchThrowable(() -> publishRequest(capabilities)); + + // then + assertThat(refused) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("capabilities must not contain null"); + } + + private static ObjectPublishRequest publishRequest( + Set capabilities) { + byte[] content = {1, 2, 3}; + return new ObjectPublishRequest( + new ObjectOperationKey( + ObjectDestinationId.of("poster"), + ObjectOperationEpoch.of("epoch-a"), + ObjectOperationId.of("operation-a")), + ObjectMediaType.of("application/octet-stream"), + new ObjectContentIdentity(content.length, ObjectDigest.sha256(content)), + ObjectPublicationRequirement.INTEGRITY_VERIFIED, + ObjectRetentionRequirement.NONE, + ObjectEncryptionRequirement.PROVIDER_MANAGED, + capabilities, + CallBudget.fromNow(Duration.ofMinutes(1)), + CancellationView.never()); + } +} From b44aa49e7abfcbb6eb159b03f1dd7898b1072d3d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 08:40:23 +0900 Subject: [PATCH 2/5] =?UTF-8?q?fix(build-logic):=20=EC=88=9C=EC=88=98=20?= =?UTF-8?q?=EB=AA=A8=EB=93=88=20testFixtures=20classpath=EB=8F=84=20?= =?UTF-8?q?=EC=88=9C=EC=88=98=EC=84=B1=20=EA=B2=80=EC=82=AC=EC=97=90=20?= =?UTF-8?q?=EB=84=A3=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: verifyModuleDependencyPurity는 순수 모듈(application-*, domain-core, shared-contract)의 compile·runtime·test classpath만 풀어 봤다. test classpath는 testFixturesImplementation을 거쳐 보지만 testFixturesCompileOnly는 보지 않는다. 그래서 공유 fixtures에 Spring을 compileOnly로 두면 순수성 검사를 통과했다. testFixtures를 쓰는 순수 leaf 다섯 곳에 같은 구멍이 있었다. 고친 것: java-test-fixtures를 쓴 순수 모듈은 testFixturesCompileClasspath· testFixturesRuntimeClasspath도 같은 금지 group으로 본다. 지금 다섯 leaf의 fixtures에는 금지 group이 없어 기존 빌드는 그대로 통과한다(lockfile 대조). 검증: desktop, 기준 4ca61cd9 + 새 functional 시험만 → testFixturesCompileOnly Spring 케이스가 빌드 통과로 실패(RED). 고친 뒤 -p build-logic test 통과(다음 커밋의 GREEN 실행에 포함). Refs: RR9-04-47 --- .../architecture/ArchitecturePlugin.java | 12 ++ ...oduleTestFixturesPurityFunctionalTest.java | 125 ++++++++++++++++++ 2 files changed, 137 insertions(+) create mode 100644 build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/PureModuleTestFixturesPurityFunctionalTest.java diff --git a/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java b/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java index 4e5491b4..34e2d3e7 100644 --- a/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java +++ b/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java @@ -26,6 +26,11 @@ public final class ArchitecturePlugin implements Plugin { private static final List APPLICATION_CLASSPATHS = List.of( "compileClasspath", "runtimeClasspath", "testCompileClasspath", "testRuntimeClasspath"); + // Present only where a pure module applies java-test-fixtures. The test classpaths above see + // testFixturesImplementation, but not testFixturesCompileOnly: a framework declared there + // compiled into the shared fixtures and passed the purity check. + private static final List TEST_FIXTURES_CLASSPATHS = + List.of("testFixturesCompileClasspath", "testFixturesRuntimeClasspath"); @Override public void apply(Project project) { @@ -171,6 +176,13 @@ public final class ArchitecturePlugin implements Plugin { .getResolutionResult() .getRootComponent()); } + for (String name : TEST_FIXTURES_CLASSPATHS) { + Configuration fixtures = application.getConfigurations().findByName(name); + if (fixtures != null) { + classpathRoots.put( + name, fixtures.getIncoming().getResolutionResult().getRootComponent()); + } + } String applicationPath = module.gradlePath(); application .getTasks() diff --git a/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/PureModuleTestFixturesPurityFunctionalTest.java b/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/PureModuleTestFixturesPurityFunctionalTest.java new file mode 100644 index 00000000..00517d81 --- /dev/null +++ b/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/PureModuleTestFixturesPurityFunctionalTest.java @@ -0,0 +1,125 @@ +package dev.caskeleton.buildlogic.architecture; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +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.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** The purity check covers a pure module's test fixtures, not only its main and test classpaths. */ +class PureModuleTestFixturesPurityFunctionalTest { + + @Test + @DisplayName("순수 모듈의 testFixturesCompileOnly에 Spring을 두면 순수성 검사가 실패한다") + void aFrameworkInAPureModulesFixturesFailsThePurityCheck(@TempDir Path temporaryRoot) + throws IOException { + // given + Path project = + fixture( + temporaryRoot, "testFixturesCompileOnly 'org.springframework:spring-context:1.0.0'"); + + // when + BuildResult result = runner(project, "verifyApplicationCoreDependencyPurity").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("testFixturesCompileClasspath: forbidden resolved dependency") + .contains("org.springframework:spring-context:1.0.0"); + } + + @Test + @DisplayName("순수 모듈의 testFixtures가 framework를 쓰지 않으면 순수성 검사를 통과한다") + void pureFixturesPassThePurityCheck(@TempDir Path temporaryRoot) throws IOException { + // given + Path project = fixture(temporaryRoot, "testFixturesImplementation 'org.example:other:1.0.0'"); + + // when + BuildResult result = runner(project, "verifyApplicationCoreDependencyPurity").build(); + + // then + assertThat(result.getOutput()).contains("verifyApplicationCoreDependencyPurity: OK"); + } + + private static Path fixture(Path temporaryRoot, String fixturesDeclaration) throws IOException { + Path project = temporaryRoot.resolve("repository"); + Files.createDirectories(project.resolve("gradle")); + Files.createDirectories(project.resolve("application-demo")); + Path maven = temporaryRoot.resolve("maven"); + pom(maven, "org.springframework", "spring-context"); + pom(maven, "org.example", "other"); + Files.writeString( + project.resolve("settings.gradle"), + """ + rootProject.name = 'main' + include 'application-demo' + """, + UTF_8); + Files.writeString( + project.resolve("build.gradle"), + """ + plugins { id 'ca.architecture' } + subprojects { + apply plugin: 'java-library' + apply plugin: 'java-test-fixtures' + repositories { maven { url = '%s' } } + } + project(':application-demo') { + dependencies { + %s + } + } + """ + .formatted(maven.toUri(), fixturesDeclaration), + UTF_8); + Files.writeString( + project.resolve("gradle/modules.json"), + """ + { + "library_groups": ["dev.cakit"], + "modules": [ + { + "id": "application-demo", + "gradle_path": ":application-demo", + "source_path": "application-demo", + "allowed_dependencies": [] + } + ] + } + """, + UTF_8); + return project; + } + + private static void pom(Path maven, String group, String artifact) throws IOException { + Path directory = maven.resolve(group.replace('.', '/')).resolve(artifact).resolve("1.0.0"); + Files.createDirectories(directory); + Files.writeString( + directory.resolve(artifact + "-1.0.0.pom"), + """ + + 4.0.0 + %s%s1.0.0 + pom + + """ + .formatted(group, artifact), + UTF_8); + } + + private static GradleRunner runner(Path project, String... arguments) { + String[] fullArguments = new String[arguments.length + 2]; + fullArguments[0] = "--console=plain"; + fullArguments[1] = "--stacktrace"; + System.arraycopy(arguments, 0, fullArguments, 2, arguments.length); + return GradleRunner.create() + .withProjectDir(project.toFile()) + .withPluginClasspath() + .withArguments(fullArguments); + } +} From 1ab96de01d5707336db5fe36bd26ddf9266b167d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 08:40:45 +0900 Subject: [PATCH 3/5] =?UTF-8?q?test(objectstorage):=20=ED=8F=AC=ED=8A=B8?= =?UTF-8?q?=20=EA=B3=84=EC=95=BD=EC=9D=84=20=ED=8F=AC=ED=8A=B8=20=EC=86=8C?= =?UTF-8?q?=EC=9C=A0=20leaf=EC=97=90=20=EB=91=90=EA=B3=A0=20fake=EC=99=80?= =?UTF-8?q?=20adapter=EA=B0=80=20=ED=95=A8=EA=BB=98=20=ED=86=B5=EA=B3=BC?= =?UTF-8?q?=ED=95=98=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: capability 기준 5(docs/manual/10-capabilities.md)는 포트를 가진 모듈의 testFixtures에 포트 계약을 두고 fake와 실제 adapter가 모두 통과하게 한다. application-objectstorage에는 testFixtures도 fake도 없었다. 포트 수준 동작은 adapter 안의 local-dev 시험으로만 봤고, 포트 인터페이스는 결과와 예외를 적지 않았다. capability-status는 app-bootstrap 통합 시험이 MinIO로 조립한다고 적었지만 실제로는 local-dev다. 고친 것: - 포트 여덟의 Javadoc에 결과(APPLIED·REPLAYED·REJECTED 등)와 예외 타입을 적었다. IllegalArgumentException은 요청 그대로를, IllegalStateException은 지금 상태에서의 거절이다. 유스케이스가 감싸 기능 오류로 바꾸고, 설정이 틀린 destination은 조립 오류(500)로 바꾼다(AGENTS 규칙). 예외 메시지는 구현의 것이라 계약이 단언하지 않는다. - testFixtures testkit: 계약 셋(ManagedObjectStoragePortContract 관리 게시·조회· 전송·복구 조회·회수, StagedObjectPublicationPortContract 단계 게시·handoff·중단, ObjectScanMaintenancePortContract scan gate), in-memory fake InMemoryObjectStorage, destination 설명 ObjectStorageDestinationPolicy. - fake(이 leaf test)와 adapter routing 구현(local-dev, adapter test contract/LocalDev*)이 같은 계약을 상속한다. adapter 쪽 destination 설명은 조립된 policySnapshot에서 읽는다. - adapter에서 계약이 드러낸 것 둘: - 실패한 managed 게시를 다시 하면 이번 호출이 게시했는데도 REPLAYED였다(stage 재시도는 APPLIED). 이제 PUBLISHED로 바꾼 호출 하나만 APPLIED다. 같은 key로 겹친 호출은 REPLAYED다(ManagedPublicationOutcomeTest가 겹침을 결정적으로 재현한다). - 검증한 뒤 중단한 stage를 다시 검증하면 REPLAYED였다. 중단된 operation의 검증을 거절한다. - 문서: application-objectstorage AGENTS·README, adapter README 「포트 계약」, TESTING_STRATEGY 9.4, capability-status Object storage 증거 칸. 버린 대안: MinIO에서 포트 계약 돌리기. S3 provider는 readiness registry에서 아직 배포 대상이 아니다(docs/registries/object-storage-readiness.yaml). 포트 경로를 MinIO로 묶는 일은 S3를 배포 대상으로 올리는 일과 같이 간다. MinIO에서는 provider 계약이 돈다. 남은 것: adapter 전용 ObjectStorageProviderException이 포트 밖으로 나가 바이트 불일치·consumer 실패는 계약이 unchecked 예외까지만 단언한다(RR9-03-34, 따로 고친다). 검증: desktop, :application-objectstorage:check :adapter:outbound:objectstorage:check :app-bootstrap:architectureTest architectureCheck -p build-logic test 726건 실패 0. RED: main에 ManagedPublicationOutcomeTest만 → 실패. 돌연변이: adapter의 회수 재시도를 REPLAYED→APPLIED로 바꾸면 계약 1건이 실패한다. Refs: RR9-03-31, RR9-03-35, RR9-04-46 --- docs/capability-status.md | 2 +- docs/testing/TESTING_STRATEGY.md | 34 + src/adapter/outbound/objectstorage/README.md | 7 + .../outbound/objectstorage/build.gradle | 5 + .../ManagedObjectPublicationKernel.java | 9 +- .../kernel/StagedObjectPublicationKernel.java | 5 + ...alDevManagedObjectStorageContractTest.java | 61 ++ ...lDevObjectScanMaintenanceContractTest.java | 67 ++ .../contract/LocalDevObjectStorage.java | 105 +++ ...evStagedObjectPublicationContractTest.java | 55 ++ .../kernel/ManagedPublicationOutcomeTest.java | 221 +++++ src/application/objectstorage/AGENTS.md | 6 +- src/application/objectstorage/README.md | 3 + src/application/objectstorage/build.gradle | 12 + src/application/objectstorage/gradle.lockfile | 54 +- .../port/ManagedObjectPublicationPort.java | 25 +- .../port/ObjectInspectionPort.java | 11 +- .../port/ObjectOperationResolutionPort.java | 12 +- .../port/ObjectPublicationHandoffPort.java | 34 +- .../port/ObjectRetirementPort.java | 13 +- .../port/ObjectScanMaintenancePort.java | 21 +- .../port/ObjectTransferPort.java | 15 +- .../port/StagedObjectPublicationPort.java | 40 +- ...emoryManagedObjectStorageContractTest.java | 47 + ...moryObjectScanMaintenanceContractTest.java | 53 ++ ...ryStagedObjectPublicationContractTest.java | 41 + .../testkit/InMemoryObjectStorage.java | 831 ++++++++++++++++++ .../ManagedObjectStoragePortContract.java | 518 +++++++++++ .../ObjectScanMaintenancePortContract.java | 359 ++++++++ .../ObjectStorageDestinationPolicy.java | 60 ++ .../testkit/ObjectStorageIdentities.java | 24 + .../ObjectStoragePortContractSupport.java | 162 ++++ .../StagedObjectPublicationPortContract.java | 634 +++++++++++++ 33 files changed, 3507 insertions(+), 39 deletions(-) create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevManagedObjectStorageContractTest.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectScanMaintenanceContractTest.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectStorage.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevStagedObjectPublicationContractTest.java create mode 100644 src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedPublicationOutcomeTest.java create mode 100644 src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryManagedObjectStorageContractTest.java create mode 100644 src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectScanMaintenanceContractTest.java create mode 100644 src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryStagedObjectPublicationContractTest.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectStorage.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ManagedObjectStoragePortContract.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectScanMaintenancePortContract.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageDestinationPolicy.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageIdentities.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStoragePortContractSupport.java create mode 100644 src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/StagedObjectPublicationPortContract.java diff --git a/docs/capability-status.md b/docs/capability-status.md index 2302c0a3..d6a56756 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -37,7 +37,7 @@ lanes and CI; it is not a deployment artifact. | File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `main.yml` → `main` (`:integrationCheck`) | | Outbound HTTP client | `app.httpclient.enabled` / `APP_HTTPCLIENT_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:httpclient')`) | yes | On when present (`HttpClientPlatformActivationTest`). `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `main.yml` → `main` (`:integrationCheck`) | | GraphQL transport | `backend.graphql.enabled` / `APP_GRAPHQL_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:graphql')`) | leaf-level | On when present; `false` also excludes Spring GraphQL's own auto-configuration, so no `/graphql` (`GraphQlCapabilityActivationTest`). `graphqlTransportQualificationTest` runs the HTTP boundary. The deployment-mode/runtime-profile rule is the module's own `GraphQlPlatformStartupValidator`. The default jar does not ship GraphQL, so a compose lane that exercises it runs the qualification jar. | -| Object storage | `app.object-storage.enabled` / `APP_OBJECTSTORAGE_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it against digest-pinned MinIO. | +| Object storage | `app.object-storage.enabled` / `APP_OBJECTSTORAGE_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:objectstorage')`) | MinIO only | Own `ObjectStorageAutoConfiguration` (was bound through bootstrap's properties scan); on when present, `false` leaves only the explicit legacy seam (`ObjectStorageAutoConfigurationTest`). `app-bootstrap:integrationTest` assembles it on the local-dev provider (`ObjectStorageCompositionIntegrationTest`). The ports are held to the application-objectstorage port contracts by the in-memory fake and by the adapter on local-dev; the S3 provider is held to `ObjectStorageProviderContract` against digest-pinned MinIO by `objectStorageMinioContractTest`, run by `main.yml` → `main` (`:integrationCheck`). | | gRPC platform | — (separate repository) | no | **no** | no | Moved out on 2026-11-08 to the `grpc-library` repository (Maven group `dev.cakit.grpc`); this repository builds and tests none of it. `adapter:inbound:grpc` uses `io.grpc` directly and is unaffected. See `docs/work/reference/related-repos.md`. | | gRPC transport (`adapter:inbound:grpc`) | `app.grpc.server.enabled` / `APP_GRPC_SERVER_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:grpc')`) | leaf-level | Own `AutoConfiguration.imports` (`GrpcServerConfig`); on when present, and the loopback plaintext listener still needs `app.grpc.server.allow-insecure-local=true` (`GrpcSafeActivationTest`, `grpcTransportQualificationTest`). | | WebSocket transport | `app.websocket.enabled` / `APP_WEBSOCKET_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:inbound:websocket')`) | — | Own `AutoConfiguration.imports` (`WebSocketConfig`), on in a servlet app when present (`WebSocketAutoConfigurationTest`); `ConditionalTransportBuildContractTest` asserts it has no default production edge. | diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index c8ff69f5..1eb8c081 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -372,6 +372,40 @@ testFixtures(`dev.caskeleton.application.fileserver.testkit`)에 있고, 실제 - 소유자 규칙: fake와 실제 정책이 같은 규칙을 따로 썼다(principal·tenant 비교 두 벌). 정본 `FileAccessSubject.owns` 하나를 둘 다 부른다. fake 규칙에서 tenant 비교를 빼는 변이가 계약 2건으로 잡힌다. +### 9.4 application-objectstorage 포트 (2026-11-13 round9 리뷰 RR9-03-31) + +포트 8개. 계약 셋과 fake는 `application-objectstorage` testFixtures(`dev.caskeleton.application.objectstorage.testkit`)에 +있다. 실제 구현 쪽은 adapter `test`의 `contract` 패키지가 local-dev provider 위에서 돌린다. 계약은 각 포트 +Javadoc이 선언한 결과와 예외 타입만 단언한다. 예외 메시지는 구현의 것이라 단언하지 않는다. + +| 포트 | 계약 | fake | 상속하는 실제 구현 테스트 | +| --- | --- | --- | --- | +| `ManagedObjectPublicationPort`·`ObjectInspectionPort`·`ObjectTransferPort`·`ObjectOperationResolutionPort`·`ObjectRetirementPort` | `ManagedObjectStoragePortContract` | `InMemoryObjectStorage` | `LocalDevManagedObjectStorageContractTest` | +| `StagedObjectPublicationPort`·`ObjectPublicationHandoffPort` | `StagedObjectPublicationPortContract` | 같은 fake | `LocalDevStagedObjectPublicationContractTest` | +| `ObjectScanMaintenancePort` | `ObjectScanMaintenancePortContract` | 같은 fake | `LocalDevObjectScanMaintenanceContractTest` | + +- 실제 벤더: S3 provider는 readiness registry(`docs/registries/object-storage-readiness.yaml`)에서 아직 배포 + 대상이 아니다. MinIO에서는 provider 계약(`ObjectStorageProviderContract`, `objectStorageMinioContractTest`)이 + 돈다. 포트 계약을 MinIO로 묶는 일은 S3를 배포 대상으로 올릴 때 같이 한다. +- 소비자 없는 fake(9.2, 결정 2026-11-03)의 예외: 이 fake의 소비자는 객체 저장소를 쓰는 서비스의 유스케이스 + 시험이다. 템플릿 안에는 그런 유스케이스가 없지만 capability 기준 5(`docs/manual/10-capabilities.md`)가 fake를 + 요구한다(round9 리뷰 6절 ⑧). +- lease 만료 경로(만료 뒤 다른 claimant, 만료된 claim의 finalize)는 계약에 없다. 계약의 lease는 5분이고 + 시계를 움직이지 않는다. adapter 쪽은 `StagedObjectPublicationLifecycleTest`가 고정 시계로 본다. + +계약을 처음 적용할 때 드러난 것과 처리: + +- 운영 결함: 불변 Set(`Set.of`)으로 만든 게시·stage 요청이 `ObjectRequestSupport`의 `contains(null)`에서 NPE를 + 냈다. 원소를 도는 검사로 고쳤다(`ObjectRequestCapabilitiesTest`). +- adapter: 실패한 managed 게시를 다시 하면 이번 호출이 게시했는데도 `REPLAYED`였다(stage는 `APPLIED`). 이제 + `PUBLISHED`로 바꾼 호출 하나만 `APPLIED`다(같은 key로 겹친 호출은 `REPLAYED`, `ManagedPublicationOutcomeTest`). + 검증한 뒤 중단한 stage를 다시 검증하면 `REPLAYED`였다. 이제 중단된 operation의 검증은 거절한다. +- fake를 실제에 맞춘 것: 실패한 게시·stage도 operation을 남긴다(복구 조회는 진행 중), 범위를 끝까지 읽지 않은 + consumer를 거절한다, capability 집합은 같은 의도 판정에 넣지 않는다, 중단한 stage의 검증을 거절하고 판정 + 뒤에도 중단으로 둔다. +- adapter 전용 예외 `ObjectStorageProviderException`이 포트 밖으로 나간다. 그래서 바이트 불일치와 consumer + 실패는 계약이 "unchecked 예외"까지만 단언한다(round9 리뷰 RR9-03-34, 따로 고친다). + ### 9.2 계약이 없는 포트 (의도) | 포트 | 실제 구현 | fake | 계약이 없는 이유 | 다음 단계 | diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index c8b38502..b2d2bc63 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -84,6 +84,13 @@ Spring Boot가 `software.amazon.awssdk:*`를 관리하지 않으니 AWS SDK v2 B ./gradlew :adapter:outbound:objectstorage:check --console=plain ``` +### 포트 계약 + +이 leaf의 포트 구현(`RoutingObjectMutationAdapter`, `RoutingObjectReadAdapter`, `ObjectPublicationHandoffService`, +`RoutingObjectScanMaintenanceAdapter`)은 application-objectstorage testFixtures의 포트 계약 셋을 local-dev +provider 위에서 상속한다(`contract/LocalDev*ContractTest`). in-memory fake도 같은 계약을 상속한다. 포트 동작을 +바꾸면 두 쪽이 함께 통과해야 한다. + ### 새 provider를 위한 provider 계약 `ObjectStorageProvider` SPI가 이 leaf의 것이므로 `ObjectStorageProviderContract`는 이 leaf의 test fixtures에 diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index 61819c9d..abc5e347 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -93,6 +93,11 @@ dependencies { testFixturesApi project(':application-objectstorage') testFixturesApi 'org.junit.jupiter:junit-jupiter-api' testFixturesImplementation 'org.assertj:assertj-core' + + // The port owner's contracts (application-objectstorage testFixtures): the routing adapters on + // the local-dev provider extend the same managed, staged and scan contracts the in-memory fake + // does (capability criterion 5). + testImplementation testFixtures(project(':application-objectstorage')) } def objectStorageReadinessRegistry = rootProject.projectDir.toPath() diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java index cd1ced75..f81b9ff7 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedObjectPublicationKernel.java @@ -75,7 +75,11 @@ public final class ManagedObjectPublicationKernel { if (reserved.decision() == ObjectOperationKernelResult.Decision.CONFLICT) { throw new IllegalArgumentException("operation identity conflicts with a different intent"); } - boolean replay = reserved.decision() != ObjectOperationKernelResult.Decision.RESERVED; + // APPLIED only for the call whose transition to PUBLISHED succeeded; every other call under + // the key is REPLAYED. A retry that finishes an attempt which failed or crashed before + // publishing makes that transition and is APPLIED; a call that another call overtook to + // PUBLISHED is not. Staged finalize answers the same way: the CAS winner is APPLIED. + boolean publishedHere = false; ObjectStorageProvider.StoredData stored = continueDataPublication( kernel, @@ -103,6 +107,7 @@ public final class ManagedObjectPublicationKernel { PublicationOperationState.PUBLISHED, stored.contentIdentity(), clock.instant()); + publishedHere = true; } } ObjectOperationRecord terminal = requireOperation(request); @@ -115,7 +120,7 @@ public final class ManagedObjectPublicationKernel { stored.exactVersion(), stored.contentIdentity(), request.declaredMediaType(), - replay ? ObjectMutationOutcome.REPLAYED : ObjectMutationOutcome.APPLIED, + publishedHere ? ObjectMutationOutcome.APPLIED : ObjectMutationOutcome.REPLAYED, terminal.updatedAt(), runtime.destination().policySnapshot().policyRevision().value()); } diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationKernel.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationKernel.java index fa205153..88226aac 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationKernel.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/StagedObjectPublicationKernel.java @@ -184,6 +184,11 @@ public final class StagedObjectPublicationKernel { if (!stage.exactVersion().equals(request.exactVersion())) { throw new IllegalArgumentException("stage version conflicts"); } + // An abort retired the staged bytes. Verifying what is gone — or replaying a verification + // made before the abort — would tell the caller the stage is still usable. + if (loadOperation(request.operationKey()).stablePhase() == PublicationOperationState.ABORTED) { + throw new IllegalStateException("staged operation was aborted"); + } ObjectStagedObjectRecord verified = stage; ObjectMutationOutcome outcome = ObjectMutationOutcome.REPLAYED; if (!stage.integrityVerified()) { diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevManagedObjectStorageContractTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevManagedObjectStorageContractTest.java new file mode 100644 index 00000000..328aa131 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevManagedObjectStorageContractTest.java @@ -0,0 +1,61 @@ +package dev.caskeleton.adapter.outbound.objectstorage.contract; + +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectRetirementPort; +import dev.caskeleton.application.objectstorage.port.ObjectTransferPort; +import dev.caskeleton.application.objectstorage.testkit.ManagedObjectStoragePortContract; +import dev.caskeleton.application.objectstorage.testkit.ObjectStorageDestinationPolicy; +import java.nio.file.Path; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; + +/** The adapter on its local-dev provider held to the managed publication contract. */ +class LocalDevManagedObjectStorageContractTest extends ManagedObjectStoragePortContract { + + @TempDir Path root; + + private LocalDevObjectStorage storage; + + @BeforeEach + void assemble() { + storage = new LocalDevObjectStorage(root); + } + + @AfterEach + void close() { + storage.close(); + } + + @Override + protected ObjectStorageDestinationPolicy destination() { + return storage.destination(LocalDevObjectStorage.POSTER); + } + + @Override + protected ManagedObjectPublicationPort publication() { + return storage.mutation; + } + + @Override + protected ObjectInspectionPort inspection() { + return storage.read; + } + + @Override + protected ObjectTransferPort transfer() { + return storage.read; + } + + @Override + protected ObjectOperationResolutionPort resolution() { + return storage.mutation; + } + + @Override + protected ObjectRetirementPort retirement() { + return storage.mutation; + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectScanMaintenanceContractTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectScanMaintenanceContractTest.java new file mode 100644 index 00000000..294b0e4b --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectScanMaintenanceContractTest.java @@ -0,0 +1,67 @@ +package dev.caskeleton.adapter.outbound.objectstorage.contract; + +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.ObjectScanMaintenancePort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.testkit.ObjectScanMaintenancePortContract; +import dev.caskeleton.application.objectstorage.testkit.ObjectStorageDestinationPolicy; +import java.nio.file.Path; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; + +/** The adapter on its local-dev provider held to the scan-gated destination contract. */ +class LocalDevObjectScanMaintenanceContractTest extends ObjectScanMaintenancePortContract { + + @TempDir Path root; + + private LocalDevObjectStorage storage; + + @BeforeEach + void assemble() { + storage = new LocalDevObjectStorage(root); + } + + @AfterEach + void close() { + storage.close(); + } + + @Override + protected ObjectStorageDestinationPolicy destination() { + return storage.destination(LocalDevObjectStorage.SCANNED); + } + + @Override + protected ObjectScanMaintenancePort scan() { + return storage.scan; + } + + @Override + protected StagedObjectPublicationPort staged() { + return storage.mutation; + } + + @Override + protected ObjectPublicationHandoffPort handoff() { + return storage.handoff; + } + + @Override + protected ManagedObjectPublicationPort publication() { + return storage.mutation; + } + + @Override + protected ObjectInspectionPort inspection() { + return storage.read; + } + + @Override + protected ObjectOperationResolutionPort resolution() { + return storage.mutation; + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectStorage.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectStorage.java new file mode 100644 index 00000000..4e14adfd --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevObjectStorage.java @@ -0,0 +1,105 @@ +package dev.caskeleton.adapter.outbound.objectstorage.contract; + +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageBindingCompiler; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilityAssembler; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilitySettings; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageDestinationSettings; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageProviderSettings; +import dev.caskeleton.adapter.outbound.objectstorage.filesystem.FilesystemLocalDevProviderContribution; +import dev.caskeleton.adapter.outbound.objectstorage.kernel.ObjectPolicySnapshot; +import dev.caskeleton.adapter.outbound.objectstorage.kernel.ObjectPublicationHandoffService; +import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutationAdapter; +import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectReadAdapter; +import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectScanMaintenanceAdapter; +import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; +import dev.caskeleton.application.objectstorage.testkit.ObjectStorageDestinationPolicy; +import java.nio.file.Path; +import java.time.Clock; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.springframework.util.unit.DataSize; + +/** + * The adapter's port implementations over its local-dev filesystem provider, assembled the way + * {@code ObjectStorageCapabilityConfig} and {@code ObjectStorageScanMaintenanceConfig} assemble + * them, for the application-objectstorage port contracts. + * + *

Two destinations: {@link #POSTER} (integrity-verified) and {@link #SCANNED} (scan-gated). + * {@link #destination(String)} describes each with the policy the binding compiler gave it. + */ +final class LocalDevObjectStorage implements AutoCloseable { + + static final String POSTER = "poster"; + static final String SCANNED = "scanned"; + private static final long MAXIMUM_OBJECT_BYTES = 1024; + + final RoutingObjectMutationAdapter mutation; + final RoutingObjectReadAdapter read; + final ObjectPublicationHandoffService handoff; + final RoutingObjectScanMaintenanceAdapter scan; + private final ObjectStorageCapabilityAssembler.AssembledCapability capability; + + LocalDevObjectStorage(Path root) { + FilesystemLocalDevProviderContribution local = new FilesystemLocalDevProviderContribution(); + capability = + new ObjectStorageCapabilityAssembler( + List.of(local), + new ObjectStorageBindingCompiler(List.of(local), Set.of("test"), true)) + .assemble(settings(root)); + Clock clock = Clock.systemUTC(); + mutation = new RoutingObjectMutationAdapter(capability, clock); + read = new RoutingObjectReadAdapter(capability); + handoff = new ObjectPublicationHandoffService(capability, clock); + scan = new RoutingObjectScanMaintenanceAdapter(capability, clock); + } + + /** + * The contract's description of {@code id}, read from the policy the binding compiler produced, + * so a compiled limit or requirement that changes changes what the contract asks for. + */ + ObjectStorageDestinationPolicy destination(String id) { + ObjectDestinationId destination = ObjectDestinationId.of(id); + ObjectPolicySnapshot policy = + capability.destination(destination).destination().policySnapshot(); + return new ObjectStorageDestinationPolicy( + destination, + policy.publicationRequirement(), + policy.retentionRequirement(), + policy.encryptionRequirement(), + policy.capabilityRequirements(), + policy.maximumObjectBytes()); + } + + @Override + public void close() { + capability.close(); + } + + private static ObjectStorageCapabilitySettings settings(Path root) { + return new ObjectStorageCapabilitySettings( + true, + POSTER, + Map.of( + "local", + new ObjectStorageProviderSettings( + "filesystem-local-dev", + "jdk-21", + root.resolve("object-storage-v1").toString(), + DataSize.ofBytes(MAXIMUM_OBJECT_BYTES), + DataSize.ofBytes(64), + null)), + Map.of( + POSTER, + destinationSettings("0123456789ab", ObjectPublicationRequirement.INTEGRITY_VERIFIED), + SCANNED, + destinationSettings("0123456789ac", ObjectPublicationRequirement.SCAN_CLEAN))); + } + + private static ObjectStorageDestinationSettings destinationSettings( + String routeToken, ObjectPublicationRequirement requirement) { + return new ObjectStorageDestinationSettings( + "local", routeToken, "binding-v1", "policy-v1", requirement, null, null, null, null, null); + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevStagedObjectPublicationContractTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevStagedObjectPublicationContractTest.java new file mode 100644 index 00000000..2e632206 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/contract/LocalDevStagedObjectPublicationContractTest.java @@ -0,0 +1,55 @@ +package dev.caskeleton.adapter.outbound.objectstorage.contract; + +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.testkit.ObjectStorageDestinationPolicy; +import dev.caskeleton.application.objectstorage.testkit.StagedObjectPublicationPortContract; +import java.nio.file.Path; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; + +/** The adapter on its local-dev provider held to the staged publication and handoff contract. */ +class LocalDevStagedObjectPublicationContractTest extends StagedObjectPublicationPortContract { + + @TempDir Path root; + + private LocalDevObjectStorage storage; + + @BeforeEach + void assemble() { + storage = new LocalDevObjectStorage(root); + } + + @AfterEach + void close() { + storage.close(); + } + + @Override + protected ObjectStorageDestinationPolicy destination() { + return storage.destination(LocalDevObjectStorage.POSTER); + } + + @Override + protected StagedObjectPublicationPort staged() { + return storage.mutation; + } + + @Override + protected ObjectPublicationHandoffPort handoff() { + return storage.handoff; + } + + @Override + protected ObjectInspectionPort inspection() { + return storage.read; + } + + @Override + protected ObjectOperationResolutionPort resolution() { + return storage.mutation; + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedPublicationOutcomeTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedPublicationOutcomeTest.java new file mode 100644 index 00000000..58b5d854 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/kernel/ManagedPublicationOutcomeTest.java @@ -0,0 +1,221 @@ +package dev.caskeleton.adapter.outbound.objectstorage.kernel; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.objectstorage.config.CompiledObjectStorageProvider; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageBindingCompiler; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilityAssembler; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilitySettings; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageDestinationSettings; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageProviderContribution; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageProviderSettings; +import dev.caskeleton.adapter.outbound.objectstorage.config.SelectedObjectStorageProviderFactory; +import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectControlMutation; +import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectControlRecord; +import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectControlStore; +import dev.caskeleton.adapter.outbound.objectstorage.control.ObjectOperationRecord; +import dev.caskeleton.adapter.outbound.objectstorage.filesystem.FilesystemLocalDevProviderContribution; +import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProviderDescriptor; +import dev.caskeleton.adapter.outbound.objectstorage.routing.RoutingObjectMutationAdapter; +import dev.caskeleton.application.objectstorage.content.CallBudget; +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; +import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; +import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.application.objectstorage.model.ObjectEncryptionRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectMediaType; +import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; +import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +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.junit.jupiter.api.io.TempDir; +import org.springframework.util.unit.DataSize; + +/** + * Which of two managed publications under one key is APPLIED. Two calls can overlap: the second + * reserves while the first is still uploading, and the first may reach PUBLISHED before the second + * reads the operation again. The port promises one APPLIED per publication. + */ +class ManagedPublicationOutcomeTest { + + @TempDir Path root; + + private final OvertakingControlStore control = new OvertakingControlStore(); + private ObjectStorageCapabilityAssembler.AssembledCapability capability; + private RoutingObjectMutationAdapter publication; + + @BeforeEach + void assembleLocalCapability() { + ObjectStorageProviderContribution local = + new OvertakingContribution(new FilesystemLocalDevProviderContribution(), control); + capability = + new ObjectStorageCapabilityAssembler( + List.of(local), + new ObjectStorageBindingCompiler(List.of(local), Set.of("test"), true)) + .assemble(settings(root)); + publication = new RoutingObjectMutationAdapter(capability, Clock.systemUTC()); + } + + @AfterEach + void closeCapability() { + capability.close(); + } + + @Test + @DisplayName("같은 key로 겹친 두 게시 중 PUBLISHED로 바꾼 호출만 APPLIED다") + void onlyTheCallThatPublishesIsApplied() { + // given + byte[] content = "overtaken-poster-bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8); + ObjectPublishRequest request = request(content); + AtomicReference overtaking = new AtomicReference<>(); + control.onceAfterDataUploaded( + () -> overtaking.set(publication.publish(request, producing(content)))); + + // when + ObjectPublishReceipt overtaken = publication.publish(request, producing(content)); + + // then + assertThat(List.of(overtaken.outcome(), overtaking.get().outcome())) + .as("the overtaking call published; the overtaken one only found it published") + .containsExactly(ObjectMutationOutcome.REPLAYED, ObjectMutationOutcome.APPLIED); + assertThat(overtaken.reference()).isEqualTo(overtaking.get().reference()); + } + + private static ObjectPublishRequest request(byte[] content) { + return new ObjectPublishRequest( + new ObjectOperationKey( + ObjectDestinationId.of("poster"), + ObjectOperationEpoch.of("epoch-a"), + ObjectOperationId.of("upload-1")), + ObjectMediaType.of("application/octet-stream"), + new ObjectContentIdentity(content.length, ObjectDigest.sha256(content)), + ObjectPublicationRequirement.INTEGRITY_VERIFIED, + ObjectRetentionRequirement.NONE, + ObjectEncryptionRequirement.PROVIDER_MANAGED, + EnumSet.of(ObjectCapabilityRequirement.IMMUTABLE_CREATE), + CallBudget.fromNow(Duration.ofMinutes(1)), + CancellationView.never()); + } + + private static ObjectContentProducer producing(byte[] content) { + return (context, sink) -> sink.write(content, 0, content.length); + } + + private static ObjectStorageCapabilitySettings settings(Path root) { + return new ObjectStorageCapabilitySettings( + true, + "poster", + Map.of( + "local", + new ObjectStorageProviderSettings( + "filesystem-local-dev", + "jdk-21", + root.resolve("object-storage-v1").toString(), + DataSize.ofBytes(1024), + DataSize.ofBytes(64), + null)), + Map.of( + "poster", + new ObjectStorageDestinationSettings( + "local", + "0123456789ab", + "binding-v1", + "policy-v1", + ObjectPublicationRequirement.INTEGRITY_VERIFIED, + null, + null, + null, + null, + null))); + } + + /** Local provider whose control store is {@link OvertakingControlStore}. */ + private record OvertakingContribution( + ObjectStorageProviderContribution delegate, OvertakingControlStore control) + implements ObjectStorageProviderContribution { + + @Override + public String providerType() { + return delegate.providerType(); + } + + @Override + public Set providerTypes() { + return delegate.providerTypes(); + } + + @Override + public ObjectStorageProviderDescriptor describe(ObjectStorageProviderSettings settings) { + return delegate.describe(settings); + } + + @Override + public Object compileProviderBinding( + String providerId, ObjectStorageProviderSettings settings) { + return delegate.compileProviderBinding(providerId, settings); + } + + @Override + public SelectedObjectStorageProviderFactory create(CompiledObjectStorageProvider provider) { + SelectedObjectStorageProviderFactory real = delegate.create(provider); + control.delegate = real.controlStore(); + return new SelectedObjectStorageProviderFactory(real.provider(), control, real::close); + } + } + + /** + * Control store that, once, right after the operation is recorded DATA_UPLOADED, runs another + * call to completion before the first one continues — the overlap of two calls under one key. + */ + private static final class OvertakingControlStore implements ObjectControlStore { + + private ObjectControlStore delegate; + private Runnable overtake; + + void onceAfterDataUploaded(Runnable call) { + overtake = call; + } + + @Override + public Optional read(String key) { + return delegate.read(key); + } + + @Override + public StoredControlRecord create(String key, ObjectControlRecord record) { + return delegate.create(key, record); + } + + @Override + public StoredControlRecord compareAndSet(String key, ObjectControlMutation mutation) { + StoredControlRecord written = delegate.compareAndSet(key, mutation); + if (overtake != null + && mutation.replacement() instanceof ObjectOperationRecord operation + && operation.stablePhase() == PublicationOperationState.DATA_UPLOADED) { + Runnable call = overtake; + overtake = null; + call.run(); + } + return written; + } + } +} diff --git a/src/application/objectstorage/AGENTS.md b/src/application/objectstorage/AGENTS.md index 1543a289..6151355f 100644 --- a/src/application/objectstorage/AGENTS.md +++ b/src/application/objectstorage/AGENTS.md @@ -13,12 +13,16 @@ - 객체 저장소를 쓰는 쪽이 보는 포트와 그 값 타입: 전송(`ObjectTransferPort`), 검사, 게시(staged·managed), 회수, 결과 확인. - `model`·`request`·`identity`·`content`의 값 타입. 구현은 `adapter:outbound:objectstorage` 하나다. +- testFixtures `testkit`: 포트 계약 셋(`ManagedObjectStoragePortContract` 관리 게시·조회·회수, `StagedObjectPublicationPortContract` 단계 게시와 handoff, `ObjectScanMaintenancePortContract` scan gate)과 in-memory fake `InMemoryObjectStorage`. 서비스의 유스케이스 시험은 그 fake를 쓴다. ## 규칙 - framework·AWS SDK 의존이 없다(`ca.java-library`). 허용 의존은 registry의 `application-core`·`shared-contract`뿐이다. - S3·MinIO 개념(bucket 정책, presign 구현)은 adapter의 것이다. 포트는 저장소에 상관없는 말로 쓴다. -- 이 leaf에는 포트 계약 시험이 아직 없다. adapter testFixtures의 `ObjectStorageProviderContract`는 adapter 안의 provider SPI를 시험하고, 이 leaf의 포트는 시험하지 않는다. 값 타입(`model`·`request`·`identity`·`content`)을 바꾸면 그 provider 계약을 같은 변경에서 고친다. +- 포트나 값 타입의 약속을 바꾸면 testFixtures의 포트 계약과 fake를 같은 변경에서 고친다. fake(이 leaf `test`)와 adapter(local-dev provider, adapter `test`)가 같은 계약을 상속하므로 둘 다 통과해야 한다(`docs/manual/10-capabilities.md` 기준 5). +- adapter testFixtures의 `ObjectStorageProviderContract`는 adapter 안 provider SPI의 계약이다(local-dev와 MinIO lane이 상속). 포트 계약과 섞지 않는다. 그래도 그 시그니처가 이 leaf의 값 타입을 쓰므로, 값 타입을 바꾸면 provider 계약도 같은 변경에서 고친다. +- 포트의 결과와 예외는 각 포트 Javadoc이 정한다. `IllegalArgumentException`은 요청 그대로를 거절한 것, `IllegalStateException`은 지금 상태(다른 claimant의 claim, 검증 전, 이미 게시)에서 거절한 것이다. 둘 다 서버 결함이 아니다. 유스케이스는 그대로 던지지 않고 자기 결과나 기능 오류(상태 충돌이면 CONFLICT carrier)로 바꾼다(`docs/manual/06-errors.md`의 「서버 탓 = `IllegalStateException`」과 섞이지 않게). +- 예외: 설정되지 않았거나 scan이 필요한 destination으로 보낸 `IllegalArgumentException`은 유스케이스가 고른 destination이 틀린 것, 곧 조립 오류다. 유스케이스는 이것을 `IllegalStateException`(500)으로 바꾸고 클라이언트 오류로 가리지 않는다. ## 테스트 diff --git a/src/application/objectstorage/README.md b/src/application/objectstorage/README.md index 7e784726..5aab8af4 100644 --- a/src/application/objectstorage/README.md +++ b/src/application/objectstorage/README.md @@ -6,6 +6,7 @@ - 객체 저장소를 쓰는 쪽이 보는 포트와 그 값 타입: 전송(`ObjectTransferPort`), 검사, 게시(staged·managed), 회수, 결과 확인. - `model`·`request`·`identity`·`content`의 값 타입. 구현은 `adapter:outbound:objectstorage` 하나다. +- testFixtures `testkit`: 포트 계약 셋(`ManagedObjectStoragePortContract` 관리 게시·조회·회수, `StagedObjectPublicationPortContract` 단계 게시와 handoff, `ObjectScanMaintenancePortContract` scan gate)과 in-memory fake `InMemoryObjectStorage`. 서비스의 유스케이스 시험은 그 fake를 쓴다. - 소유하지 않는 것: S3·MinIO 호출과 설정(`adapter:outbound:objectstorage`), 파일 서버의 업로드 흐름(`application-fileserver`). ## 공개 표면 @@ -22,6 +23,8 @@ ./gradlew :application-objectstorage:test --console=plain ``` +fake가 포트 계약을 통과하는지는 이 leaf `test`가, adapter가 같은 계약을 통과하는지는 `./gradlew :adapter:outbound:objectstorage:test`가 본다. 쓰는 쪽은 `testImplementation testFixtures(project(':application-objectstorage'))`로 계약과 fake를 받는다. + ## 더 읽을 곳 - [AGENTS.md](AGENTS.md)(이 leaf의 규칙) diff --git a/src/application/objectstorage/build.gradle b/src/application/objectstorage/build.gradle index d89e6abc..b537bf38 100644 --- a/src/application/objectstorage/build.gradle +++ b/src/application/objectstorage/build.gradle @@ -1,5 +1,6 @@ plugins { id 'ca.java-library' + id 'java-test-fixtures' } // Optional object-storage application product. Provider SDKs stay in outbound adapters. @@ -10,4 +11,15 @@ dependencies { // Property-based verification for bounded identity/value contracts moved with this product. testImplementation libs.jqwik + + // The port owner's test fixtures (capability criterion 5, docs/manual/10-capabilities.md): the + // abstract port contracts (`*PortContract`) that the in-memory fake and the real adapter both + // extend, and the fake itself for a service's own use-case tests. Adapters reach them with + // `testImplementation testFixtures(project(':application-objectstorage'))`. + // ObjectPublishReceipt carries application-core's RequestFingerprint; the identities' check + // digest is shared-contract's Sha256. + testFixturesImplementation project(':application-core') + testFixturesImplementation project(':shared-contract') + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/src/application/objectstorage/gradle.lockfile b/src/application/objectstorage/gradle.lockfile index 15f18896..80eb8bdb 100644 --- a/src/application/objectstorage/gradle.lockfile +++ b/src/application/objectstorage/gradle.lockfile @@ -1,38 +1,38 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.50.0=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.50.0=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.7.2-jre=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.puppycrawl.tools:checkstyle:13.5.0=checkstyle commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.jqwik:jqwik-api:1.9.1=testCompileClasspath,testRuntimeClasspath net.jqwik:jqwik-engine:1.9.1=testRuntimeClasspath net.jqwik:jqwik-time:1.9.1=testCompileClasspath,testRuntimeClasspath @@ -53,32 +53,32 @@ org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testRuntimeClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath,testRuntimeClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.6.1=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath -org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle org.slf4j:slf4j-api:2.0.20=spotbugs,spotbugsSlf4j org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ManagedObjectPublicationPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ManagedObjectPublicationPort.java index 8708c68c..6a4facbb 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ManagedObjectPublicationPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ManagedObjectPublicationPort.java @@ -4,8 +4,31 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; -/** Managed single-call publication for destinations whose compiled policy does not require scan. */ +/** + * Managed single-call publication for destinations whose compiled policy does not require scan. + * + *

Exceptions follow one rule across the object-storage ports: {@link IllegalArgumentException} + * refuses the request as given (unknown destination or reference, a request outside the + * destination's policy, a version or intent that does not match), {@link IllegalStateException} + * refuses it in the operation's current state (claimed by another, not yet verified, already + * published). Both are refusals, not server faults: a use case translates them into its own outcome + * or feature error rather than letting them reach a transport as they are. + */ public interface ManagedObjectPublicationPort { + /** + * Publishes the producer's bytes under the request's operation key. + * + * @return {@code APPLIED} when this call published (including a retry that finishes an earlier + * attempt which failed before publishing); {@code REPLAYED} with the same reference and + * version when an earlier call already published the same key and intent, without calling the + * producer + * @throws IllegalArgumentException the destination is unknown or scan-gated, the request does not + * satisfy its policy (including content longer than its object limit), or the key already + * names a different intent + * @throws RuntimeException the produced bytes do not match the declared content identity; nothing + * is published and the operation stays in progress for a retry (the exception type is the + * implementation's) + */ ObjectPublishReceipt publish(ObjectPublishRequest request, ObjectContentProducer producer); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectInspectionPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectInspectionPort.java index cd73dbd1..f7a22242 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectInspectionPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectInspectionPort.java @@ -4,8 +4,17 @@ import dev.caskeleton.application.objectstorage.identity.ObjectReference; import dev.caskeleton.application.objectstorage.model.ObjectDescriptor; import java.util.Optional; -/** Inspects only published opaque references. */ +/** + * Inspects only published opaque references. The exception rule is {@link + * ManagedObjectPublicationPort}'s. + */ public interface ObjectInspectionPort { + /** + * The published object behind {@code reference}. + * + * @return empty when nothing is published under the reference, or it was retired + * @throws IllegalArgumentException the reference's route names no configured destination + */ Optional inspect(ObjectReference reference); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectOperationResolutionPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectOperationResolutionPort.java index 854352d3..1007c688 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectOperationResolutionPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectOperationResolutionPort.java @@ -3,8 +3,18 @@ package dev.caskeleton.application.objectstorage.port; import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; import dev.caskeleton.application.objectstorage.model.ObjectOperationResolution; -/** Read-only recovery lookup for an exact retained operation key. */ +/** + * Read-only recovery lookup for an exact retained operation key. The exception rule is {@link + * ManagedObjectPublicationPort}'s. + */ public interface ObjectOperationResolutionPort { + /** + * What became of the operation under {@code operationKey}. + * + * @return {@code REJECTED}/{@code NOT_FOUND} for a key never seen; {@code APPLIED} with the + * reference once published; {@code INDETERMINATE} with the current phase otherwise + * @throws IllegalArgumentException the key's destination is not configured + */ ObjectOperationResolution resolve(ObjectOperationKey operationKey); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectPublicationHandoffPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectPublicationHandoffPort.java index 1bdd2175..a0d559d8 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectPublicationHandoffPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectPublicationHandoffPort.java @@ -7,14 +7,46 @@ import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimReques import dev.caskeleton.application.objectstorage.request.ObjectHandoffReleaseRequest; import dev.caskeleton.application.objectstorage.request.ObjectHandoffRenewRequest; -/** Fenced handoff seam between application intent and storage publication/cleanup. */ +/** + * Fenced handoff seam between application intent and storage publication/cleanup. A contended claim + * is an {@link IllegalStateException} the caller handles, not a fault. The exception rule is {@link + * ManagedObjectPublicationPort}'s. + */ public interface ObjectPublicationHandoffPort { + /** + * Claims a stage for publication. + * + * @return {@code APPLIED} with a fence (the next one after a released claim); {@code REPLAYED} + * with the same fence when the same claimant still holds it + * @throws IllegalArgumentException the stage is unknown, belongs to another key, or the version + * is not the stage's + * @throws IllegalStateException another claimant holds an unexpired claim, or abort is authorized + */ ObjectHandoffReceipt claimForPublication(ObjectHandoffClaimRequest request); + /** + * Extends the holder's claim; the fence stays. + * + * @throws IllegalStateException the caller does not hold the active claim at that fence + */ ObjectHandoffReceipt renewClaim(ObjectHandoffRenewRequest request); + /** + * Releases the holder's claim. + * + * @return {@code APPLIED}; {@code REPLAYED} when the same claimant already released that fence + * @throws IllegalStateException the caller does not hold the active claim at that fence + */ ObjectMutationReceipt releaseClaim(ObjectHandoffReleaseRequest request); + /** + * Authorizes aborting a stage whose claim was released or expired. + * + * @return {@code APPLIED}; {@code REPLAYED} for the same fence; {@code REJECTED}/{@code CONFLICT} + * when the stage was published first + * @throws IllegalArgumentException the version is not the stage's + * @throws IllegalStateException an unexpired claim is still held, or the fence is stale + */ ObjectMutationReceipt authorizeAbort(ObjectAbortAuthorization authorization); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectRetirementPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectRetirementPort.java index f878138e..fcf25218 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectRetirementPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectRetirementPort.java @@ -3,8 +3,19 @@ package dev.caskeleton.application.objectstorage.port; import dev.caskeleton.application.objectstorage.model.ObjectMutationReceipt; import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest; -/** Logical business retirement; it does not grant physical purge authority. */ +/** + * Logical business retirement; it does not grant physical purge authority. The exception rule is + * {@link ManagedObjectPublicationPort}'s. + */ public interface ObjectRetirementPort { + /** + * Retires a published reference; it is no longer inspectable or transferable. + * + * @return {@code APPLIED}; {@code REPLAYED} when already retired; {@code REJECTED}/{@code + * CONFLICT} when the exact version is not the reference's, which stays published + * @throws IllegalArgumentException nothing is published under the reference, or the request's + * destination is not the reference's + */ ObjectMutationReceipt retire(ObjectRetireRequest request); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectScanMaintenancePort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectScanMaintenancePort.java index 07356d45..02cb9ced 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectScanMaintenancePort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectScanMaintenancePort.java @@ -8,12 +8,31 @@ import dev.caskeleton.application.objectstorage.request.ObjectScanVerdictRequest /** * Narrow scanner-workflow composition boundary for unpublished exact-version transfer and verdict - * recording. It must not share a normal publication router or privileged purge router. + * recording. It must not share a normal publication router or privileged purge router. The + * exception rule is {@link ManagedObjectPublicationPort}'s. */ public interface ObjectScanMaintenancePort { + /** + * Delivers a verified stage's exact bytes to the scanner. + * + * @return the delivered range; {@code FULL_CONTENT} when the whole stage was read + * @throws IllegalArgumentException the stage is unknown or the version is not the stage's + * @throws IllegalStateException the stage is not verified and awaiting a verdict + * @throws RuntimeException the stage was aborted, or the consumer failed or returned before + * reading the whole range (the exception type is the implementation's) + */ ObjectScanReadReceipt transferForScan( ObjectScanReadRequest request, ObjectContentConsumer consumer); + /** + * Records the scanner's terminal verdict; CLEAN lets the stage finalize, anything else + * quarantines it. A verdict on an aborted stage is recorded and the stage stays aborted. + * + * @return {@code APPLIED}; {@code REPLAYED} for the same scan operation, policy and verdict + * @throws IllegalArgumentException the stage is unknown, the version is not the stage's, or a + * different verdict is already recorded + * @throws IllegalStateException the stage is not verified and awaiting a verdict + */ ObjectMutationReceipt recordScanVerdict(ObjectScanVerdictRequest request); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectTransferPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectTransferPort.java index 1cbb4f33..5719ecf9 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectTransferPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/ObjectTransferPort.java @@ -4,8 +4,21 @@ import dev.caskeleton.application.objectstorage.content.ObjectContentConsumer; import dev.caskeleton.application.objectstorage.model.ObjectReadReceipt; import dev.caskeleton.application.objectstorage.request.ObjectReadRequest; -/** Bounded server-mediated transfer of an authorized published reference. */ +/** + * Bounded server-mediated transfer of an authorized published reference. The exception rule is + * {@link ManagedObjectPublicationPort}'s. + */ public interface ObjectTransferPort { + /** + * Delivers the requested range of a published object to the consumer. + * + * @return the delivered range; {@code FULL_CONTENT} verification only when the whole object was + * read and full verification was asked for + * @throws IllegalArgumentException the reference is unknown, not published or retired, or the + * expected version is not the object's + * @throws RuntimeException the consumer failed or returned before reading the whole range (the + * exception type is the implementation's) + */ ObjectReadReceipt transfer(ObjectReadRequest request, ObjectContentConsumer consumer); } diff --git a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/StagedObjectPublicationPort.java b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/StagedObjectPublicationPort.java index 073eedd0..06ea9717 100644 --- a/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/StagedObjectPublicationPort.java +++ b/src/application/objectstorage/src/main/java/dev/caskeleton/application/objectstorage/port/StagedObjectPublicationPort.java @@ -10,14 +10,52 @@ import dev.caskeleton.application.objectstorage.request.ObjectFinalizeRequest; import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; -/** Normal staged publication; scanner unpublished-read/verdict authority is deliberately absent. */ +/** + * Normal staged publication; scanner unpublished-read/verdict authority is deliberately absent. The + * exception rule is {@link ManagedObjectPublicationPort}'s. + */ public interface StagedObjectPublicationPort { + /** + * Stages the producer's bytes under the request's operation key. + * + * @return {@code APPLIED} when this call staged (including a retry that finishes a failed + * attempt); {@code REPLAYED} with the same stage handle and version when an earlier call + * already staged the same key and intent, without calling the producer + * @throws IllegalArgumentException the destination is unknown, the request does not satisfy its + * policy, or the key already names a different intent + * @throws RuntimeException the produced bytes do not match the declared content identity (the + * exception type is the implementation's) + */ ObjectStageReceipt stage(ObjectStageRequest request, ObjectContentProducer producer); + /** + * Verifies the staged bytes against the expected content identity. + * + * @return {@code APPLIED} the first time, {@code REPLAYED} after + * @throws IllegalArgumentException the stage is unknown, belongs to another key, or the version + * or expected content is not the stage's + * @throws IllegalStateException the stage was aborted, so its bytes are gone + */ ObjectVerificationReceipt verifyIntegrity(ObjectVerifyRequest request); + /** + * Publishes a verified stage (and, on a scan-gated destination, one with a CLEAN verdict). + * + * @return {@code APPLIED}; {@code REPLAYED} with the same reference once published + * @throws IllegalArgumentException the stage is unknown, or the version or publication + * requirement is not the stage's + * @throws IllegalStateException the caller does not hold the active publication claim at the + * given fence, the stage is not verified, or a scan-gated stage has no CLEAN verdict + */ ObjectPublishReceipt finalizePublication(ObjectFinalizeRequest request); + /** + * Aborts an unpublished stage whose abort the handoff authorized at the given fence. + * + * @return {@code APPLIED}; {@code REPLAYED} once aborted + * @throws IllegalArgumentException the stage is unknown or belongs to another key + * @throws IllegalStateException the stage is published, or no abort is authorized at that fence + */ ObjectMutationReceipt abort(ObjectAbortRequest request); } diff --git a/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryManagedObjectStorageContractTest.java b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryManagedObjectStorageContractTest.java new file mode 100644 index 00000000..ad31328d --- /dev/null +++ b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryManagedObjectStorageContractTest.java @@ -0,0 +1,47 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectRetirementPort; +import dev.caskeleton.application.objectstorage.port.ObjectTransferPort; +import java.time.Clock; + +/** The in-memory fake held to the managed publication contract. */ +class InMemoryManagedObjectStorageContractTest extends ManagedObjectStoragePortContract { + + private final ObjectStorageDestinationPolicy destination = + ObjectStorageDestinationPolicy.integrityVerified("poster", 1024); + private final InMemoryObjectStorage storage = + new InMemoryObjectStorage(Clock.systemUTC(), destination); + + @Override + protected ObjectStorageDestinationPolicy destination() { + return destination; + } + + @Override + protected ManagedObjectPublicationPort publication() { + return storage; + } + + @Override + protected ObjectInspectionPort inspection() { + return storage; + } + + @Override + protected ObjectTransferPort transfer() { + return storage; + } + + @Override + protected ObjectOperationResolutionPort resolution() { + return storage; + } + + @Override + protected ObjectRetirementPort retirement() { + return storage; + } +} diff --git a/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectScanMaintenanceContractTest.java b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectScanMaintenanceContractTest.java new file mode 100644 index 00000000..ca3671c2 --- /dev/null +++ b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectScanMaintenanceContractTest.java @@ -0,0 +1,53 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.ObjectScanMaintenancePort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import java.time.Clock; + +/** The in-memory fake held to the scan-gated destination contract. */ +class InMemoryObjectScanMaintenanceContractTest extends ObjectScanMaintenancePortContract { + + private final ObjectStorageDestinationPolicy destination = + ObjectStorageDestinationPolicy.integrityVerified("poster", 1024).scanGated(); + private final InMemoryObjectStorage storage = + new InMemoryObjectStorage(Clock.systemUTC(), destination); + + @Override + protected ObjectStorageDestinationPolicy destination() { + return destination; + } + + @Override + protected ObjectScanMaintenancePort scan() { + return storage; + } + + @Override + protected StagedObjectPublicationPort staged() { + return storage; + } + + @Override + protected ObjectPublicationHandoffPort handoff() { + return storage; + } + + @Override + protected ManagedObjectPublicationPort publication() { + return storage; + } + + @Override + protected ObjectInspectionPort inspection() { + return storage; + } + + @Override + protected ObjectOperationResolutionPort resolution() { + return storage; + } +} diff --git a/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryStagedObjectPublicationContractTest.java b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryStagedObjectPublicationContractTest.java new file mode 100644 index 00000000..92c59b67 --- /dev/null +++ b/src/application/objectstorage/src/test/java/dev/caskeleton/application/objectstorage/testkit/InMemoryStagedObjectPublicationContractTest.java @@ -0,0 +1,41 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import java.time.Clock; + +/** The in-memory fake held to the staged publication and handoff contract. */ +class InMemoryStagedObjectPublicationContractTest extends StagedObjectPublicationPortContract { + + private final ObjectStorageDestinationPolicy destination = + ObjectStorageDestinationPolicy.integrityVerified("poster", 1024); + private final InMemoryObjectStorage storage = + new InMemoryObjectStorage(Clock.systemUTC(), destination); + + @Override + protected ObjectStorageDestinationPolicy destination() { + return destination; + } + + @Override + protected StagedObjectPublicationPort staged() { + return storage; + } + + @Override + protected ObjectPublicationHandoffPort handoff() { + return storage; + } + + @Override + protected ObjectInspectionPort inspection() { + return storage; + } + + @Override + protected ObjectOperationResolutionPort resolution() { + return storage; + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectStorage.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectStorage.java new file mode 100644 index 00000000..cfeb7b3c --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/InMemoryObjectStorage.java @@ -0,0 +1,831 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.objectstorage.content.CallBudget; +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.content.ObjectChunkSink; +import dev.caskeleton.application.objectstorage.content.ObjectChunkSource; +import dev.caskeleton.application.objectstorage.content.ObjectContentConsumer; +import dev.caskeleton.application.objectstorage.content.ObjectContentConsumptionException; +import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; +import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; +import dev.caskeleton.application.objectstorage.content.ObjectContentProductionException; +import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext; +import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.identity.ObjectReference; +import dev.caskeleton.application.objectstorage.identity.ObjectStageHandle; +import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; +import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; +import dev.caskeleton.application.objectstorage.model.ObjectDescriptor; +import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.application.objectstorage.model.ObjectDigestVerification; +import dev.caskeleton.application.objectstorage.model.ObjectEncryptionRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectHandoffReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectMediaType; +import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; +import dev.caskeleton.application.objectstorage.model.ObjectMutationReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectOperationError; +import dev.caskeleton.application.objectstorage.model.ObjectOperationResolution; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationState; +import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectReadRange; +import dev.caskeleton.application.objectstorage.model.ObjectReadReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectScanReadReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectScanState; +import dev.caskeleton.application.objectstorage.model.ObjectStageReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectVerificationReceipt; +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.ObjectRetirementPort; +import dev.caskeleton.application.objectstorage.port.ObjectScanMaintenancePort; +import dev.caskeleton.application.objectstorage.port.ObjectTransferPort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.request.ObjectAbortAuthorization; +import dev.caskeleton.application.objectstorage.request.ObjectAbortRequest; +import dev.caskeleton.application.objectstorage.request.ObjectFinalizeRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffReleaseRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffRenewRequest; +import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; +import dev.caskeleton.application.objectstorage.request.ObjectReadRequest; +import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest; +import dev.caskeleton.application.objectstorage.request.ObjectScanReadRequest; +import dev.caskeleton.application.objectstorage.request.ObjectScanVerdictRequest; +import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; +import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; +import dev.caskeleton.shared.digest.Sha256; +import java.io.ByteArrayOutputStream; +import java.time.Clock; +import java.time.Instant; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** + * Every object-storage port over in-memory maps: the fake side of the port contracts in this + * package, and the object storage a service's own use-case tests run against. + * + *

It keeps the rules the ports declare — replay by operation key, refusal of a different intent + * under the same key, reads of published references only, the destination policy, the fenced + * publication handoff and the scan gate — and none of the durability or crash recovery a real store + * needs. Identities are canonical ({@code osr1}/{@code osv1}/{@code osh1} with their check digits) + * and mean nothing outside this instance. + */ +public final class InMemoryObjectStorage + implements ManagedObjectPublicationPort, + ObjectInspectionPort, + ObjectTransferPort, + ObjectOperationResolutionPort, + ObjectRetirementPort, + StagedObjectPublicationPort, + ObjectPublicationHandoffPort, + ObjectScanMaintenancePort { + + private static final String CAPABILITY_REVISION = "in-memory-v1"; + private static final int CHUNK_BYTES = 64 * 1024; + + private final Clock clock; + private final Map routesByDestination = new LinkedHashMap<>(); + private final Map routesByToken = new HashMap<>(); + + /** An object storage holding {@code destinations}, stamping receipts from {@code clock}. */ + public InMemoryObjectStorage(Clock clock, ObjectStorageDestinationPolicy... destinations) { + this.clock = Objects.requireNonNull(clock, "clock must be non-null"); + if (destinations.length == 0) { + throw new IllegalArgumentException("at least one destination is required"); + } + for (ObjectStorageDestinationPolicy destination : destinations) { + Route route = new Route(destination, hex("route:" + destination.id().value(), 12)); + if (routesByDestination.put(destination.id(), route) != null) { + throw new IllegalArgumentException("duplicate destination " + destination.id().value()); + } + routesByToken.put(route.token, route); + } + } + + // ---- managed publication --------------------------------------------------------------- + + @Override + public synchronized ObjectPublishReceipt publish( + ObjectPublishRequest request, ObjectContentProducer producer) { + Route route = route(request.operationKey().destination()); + if (route.destination.publicationRequirement() == ObjectPublicationRequirement.SCAN_CLEAN) { + throw new IllegalArgumentException( + "scan-gated destinations publish only through staged finalize"); + } + route.requirePolicy( + "request does not satisfy the destination policy", + request.publicationRequirement(), + request.retentionRequirement(), + request.encryptionRequirement(), + request.capabilityRequirements(), + request.contentIdentity()); + Intent intent = + new Intent( + "PUBLISH", + request.declaredMediaType(), + request.contentIdentity(), + request.publicationRequirement(), + request.retentionRequirement(), + request.encryptionRequirement()); + Operation operation = route.operations.get(request.operationKey()); + if (operation != null && !operation.intent.equals(intent)) { + throw new IllegalArgumentException("operation identity conflicts with a different intent"); + } + if (operation != null && operation.phase == Phase.PUBLISHED) { + return publishReceipt(route, operation, ObjectMutationOutcome.REPLAYED); + } + if (operation == null) { + // Recorded before the bytes are produced, as a durable store reserves the key first: a + // failed attempt leaves an operation in progress that resolve() reports and a retry finishes. + operation = route.newOperation(request.operationKey(), intent); + } + operation.content = + produced(producer, request.contentIdentity(), request.budget(), request.cancellation()); + operation.phase = Phase.PUBLISHED; + route.publish(operation, now()); + return publishReceipt(route, operation, ObjectMutationOutcome.APPLIED); + } + + // ---- reads -------------------------------------------------------------------------------- + + @Override + public synchronized Optional inspect(ObjectReference reference) { + Route route = routeOf(reference); + Published published = route.references.get(reference); + if (published == null || published.retired) { + return Optional.empty(); + } + Operation operation = published.operation; + return Optional.of( + new ObjectDescriptor( + reference, + operation.version, + operation.intent.contentIdentity(), + operation.intent.mediaType(), + Optional.empty(), + ObjectPublicationState.PUBLISHED, + route.destination.publicationRequirement() == ObjectPublicationRequirement.SCAN_CLEAN + ? ObjectScanState.CLEAN + : ObjectScanState.NOT_REQUIRED, + route.destination.encryptionRequirement(), + route.destination.retentionRequirement(), + published.publishedAt, + Optional.of(published.publishedAt), + 1)); + } + + @Override + public synchronized ObjectReadReceipt transfer( + ObjectReadRequest request, ObjectContentConsumer consumer) { + Route route = routeOf(request.reference()); + Published published = route.references.get(request.reference()); + if (published == null) { + throw new IllegalArgumentException("object reference is absent"); + } + if (published.retired) { + throw new IllegalArgumentException("object reference is not published"); + } + Operation operation = published.operation; + if (request.expectedVersion().isPresent() + && !request.expectedVersion().orElseThrow().equals(operation.version)) { + throw new IllegalArgumentException("object version precondition failed"); + } + deliver(operation, request.range(), request.budget(), request.cancellation(), consumer); + boolean wholeObject = + request.range().offset() == 0 && request.range().length() == operation.content.length; + return new ObjectReadReceipt( + request.reference(), + operation.version, + request.range(), + request.range().length(), + wholeObject && request.digestVerification() == ObjectDigestVerification.FULL_CONTENT + ? ObjectDigestVerification.FULL_CONTENT + : ObjectDigestVerification.NONE); + } + + @Override + public synchronized ObjectOperationResolution resolve(ObjectOperationKey operationKey) { + Route route = route(operationKey.destination()); + Operation operation = route.operations.get(operationKey); + if (operation == null) { + return new ObjectOperationResolution( + operationKey, + ObjectPublicationState.ABORTED, + ObjectMutationOutcome.REJECTED, + ObjectOperationError.NOT_FOUND, + Optional.empty()); + } + boolean published = operation.phase == Phase.PUBLISHED; + return new ObjectOperationResolution( + operationKey, + operation.phase.state, + published ? ObjectMutationOutcome.APPLIED : ObjectMutationOutcome.INDETERMINATE, + ObjectOperationError.NONE, + published ? Optional.of(operation.reference) : Optional.empty()); + } + + // ---- retirement --------------------------------------------------------------------------- + + @Override + public synchronized ObjectMutationReceipt retire(ObjectRetireRequest request) { + Route route = routeOf(request.reference()); + if (!route.destination.id().equals(request.operationKey().destination())) { + throw new IllegalArgumentException("retirement destination does not match reference route"); + } + Published published = route.references.get(request.reference()); + if (published == null) { + throw new IllegalArgumentException("published reference is absent"); + } + if (!published.operation.version.equals(request.exactVersion())) { + return mutation( + request.operationKey(), ObjectMutationOutcome.REJECTED, ObjectOperationError.CONFLICT); + } + if (published.retired) { + return mutation( + request.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE); + } + published.retired = true; + return mutation( + request.operationKey(), ObjectMutationOutcome.APPLIED, ObjectOperationError.NONE); + } + + // ---- staged publication ------------------------------------------------------------------- + + @Override + public synchronized ObjectStageReceipt stage( + ObjectStageRequest request, ObjectContentProducer producer) { + Route route = route(request.operationKey().destination()); + route.requirePolicy( + "stage request does not satisfy the destination policy", + request.publicationRequirement(), + request.retentionRequirement(), + request.encryptionRequirement(), + request.capabilityRequirements(), + request.contentIdentity()); + Intent intent = + new Intent( + "STAGE", + request.declaredMediaType(), + request.contentIdentity(), + request.publicationRequirement(), + request.retentionRequirement(), + request.encryptionRequirement()); + Operation operation = route.operations.get(request.operationKey()); + if (operation != null && !operation.intent.equals(intent)) { + throw new IllegalArgumentException("stage operation identity conflicts"); + } + if (operation != null && operation.stageHandle != null) { + return stageReceipt(operation, ObjectMutationOutcome.REPLAYED); + } + if (operation == null) { + operation = route.newOperation(request.operationKey(), intent); + } + operation.content = + produced(producer, request.contentIdentity(), request.budget(), request.cancellation()); + operation.stageHandle = + ObjectStageHandle.parse( + ObjectStorageIdentities.canonical( + "osh1", route.token, hex("stage:" + operation.objectId, 26))); + operation.scanState = + request.publicationRequirement() == ObjectPublicationRequirement.SCAN_CLEAN + ? ObjectScanState.PENDING + : ObjectScanState.NOT_REQUIRED; + route.stages.put(operation.stageHandle, operation); + return stageReceipt(operation, ObjectMutationOutcome.APPLIED); + } + + @Override + public synchronized ObjectVerificationReceipt verifyIntegrity(ObjectVerifyRequest request) { + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + if (!stage.intent.contentIdentity().equals(request.expectedContent())) { + throw new IllegalArgumentException("staged content identity conflicts"); + } + if (!stage.version.equals(request.exactVersion())) { + throw new IllegalArgumentException("stage version conflicts"); + } + if (stage.phase == Phase.ABORTED) { + // An abort removed the staged bytes; there is nothing left to verify. + throw new IllegalStateException("staged operation was aborted"); + } + ObjectMutationOutcome outcome = ObjectMutationOutcome.REPLAYED; + if (!stage.integrityVerified) { + stage.integrityVerified = true; + stage.phase = + stage.scanState == ObjectScanState.PENDING ? Phase.SCAN_PENDING : Phase.VERIFIED; + outcome = ObjectMutationOutcome.APPLIED; + } + return new ObjectVerificationReceipt( + stage.key, stage.stageHandle, stage.version, stage.intent.contentIdentity(), outcome); + } + + @Override + public synchronized ObjectPublishReceipt finalizePublication(ObjectFinalizeRequest request) { + Route route = route(request.operationKey().destination()); + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + if (!stage.version.equals(request.exactVersion()) + || stage.intent.publicationRequirement() != request.publicationRequirement()) { + throw new IllegalArgumentException("finalize intent conflicts with staged evidence"); + } + boolean allowed = + switch (stage.intent.publicationRequirement()) { + case INTEGRITY_VERIFIED -> stage.scanState == ObjectScanState.NOT_REQUIRED; + case SCAN_CLEAN -> stage.scanState == ObjectScanState.CLEAN; + }; + if (!allowed) { + throw new IllegalStateException("staged object lacks the required publication evidence"); + } + if (stage.phase == Phase.PUBLISHED) { + return publishReceipt(route, stage, ObjectMutationOutcome.REPLAYED); + } + Handoff handoff = route.handoffs.get(stage.stageHandle); + if (handoff == null || !handoff.heldBy(request.handoffFence(), request.claimant(), now())) { + throw new IllegalStateException("finalize requires the active publication claim"); + } + Phase required = + stage.intent.publicationRequirement() == ObjectPublicationRequirement.SCAN_CLEAN + ? Phase.SCAN_CLEAN + : Phase.VERIFIED; + if (stage.phase != required) { + throw new IllegalStateException("staged operation is not finalizable"); + } + stage.phase = Phase.PUBLISHED; + route.publish(stage, now()); + return publishReceipt(route, stage, ObjectMutationOutcome.APPLIED); + } + + @Override + public synchronized ObjectMutationReceipt abort(ObjectAbortRequest request) { + Route route = route(request.operationKey().destination()); + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + if (stage.phase == Phase.PUBLISHED) { + throw new IllegalStateException("published operation cannot be aborted"); + } + Handoff handoff = route.handoffs.get(stage.stageHandle); + if (handoff == null) { + throw new IllegalStateException("abort authorization is absent"); + } + if (!handoff.abortAuthorized + || handoff.fence != request.authorization().handoffFence() + || !stage.version.equals(request.authorization().exactVersion())) { + throw new IllegalStateException("abort authorization is stale or conflicts"); + } + if (stage.phase == Phase.ABORTED) { + return mutation( + request.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE); + } + stage.phase = Phase.ABORTED; + return mutation( + request.operationKey(), ObjectMutationOutcome.APPLIED, ObjectOperationError.NONE); + } + + // ---- publication handoff ------------------------------------------------------------------ + + @Override + public synchronized ObjectHandoffReceipt claimForPublication(ObjectHandoffClaimRequest request) { + Route route = route(request.operationKey().destination()); + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + if (!stage.version.equals(request.exactVersion())) { + throw new IllegalArgumentException("handoff exact version conflicts"); + } + Instant now = now(); + Handoff current = route.handoffs.get(stage.stageHandle); + if (current == null) { + Handoff claimed = new Handoff(1, request.claimant(), now.plus(request.leaseDuration())); + route.handoffs.put(stage.stageHandle, claimed); + return handoffReceipt(stage, claimed, ObjectMutationOutcome.APPLIED); + } + if (current.active(now)) { + if (current.claimant.equals(request.claimant())) { + return handoffReceipt(stage, current, ObjectMutationOutcome.REPLAYED); + } + throw new IllegalStateException("publication handoff is actively claimed"); + } + if (current.abortAuthorized) { + throw new IllegalStateException("publication handoff is abort-authorized"); + } + Handoff claimed = + new Handoff(current.fence + 1, request.claimant(), now.plus(request.leaseDuration())); + route.handoffs.put(stage.stageHandle, claimed); + return handoffReceipt(stage, claimed, ObjectMutationOutcome.APPLIED); + } + + @Override + public synchronized ObjectHandoffReceipt renewClaim(ObjectHandoffRenewRequest request) { + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + Handoff handoff = handoffOf(stage); + handoff.requireOwner(request.fence(), request.claimant(), now()); + handoff.leaseExpiresAt = now().plus(request.leaseDuration()); + return handoffReceipt(stage, handoff, ObjectMutationOutcome.APPLIED); + } + + @Override + public synchronized ObjectMutationReceipt releaseClaim(ObjectHandoffReleaseRequest request) { + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + Handoff handoff = handoffOf(stage); + if (handoff.released + && handoff.fence == request.fence() + && handoff.claimant.equals(request.claimant())) { + return mutation( + request.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE); + } + handoff.requireOwner(request.fence(), request.claimant(), now()); + handoff.released = true; + return mutation( + request.operationKey(), ObjectMutationOutcome.APPLIED, ObjectOperationError.NONE); + } + + @Override + public synchronized ObjectMutationReceipt authorizeAbort(ObjectAbortAuthorization authorization) { + Operation stage = stageOf(authorization.operationKey(), authorization.stageHandle()); + if (!stage.version.equals(authorization.exactVersion())) { + throw new IllegalArgumentException("abort exact version conflicts"); + } + if (stage.phase == Phase.PUBLISHED) { + // The publication finished first and wins: a typed refusal, not an exception. + return mutation( + authorization.operationKey(), + ObjectMutationOutcome.REJECTED, + ObjectOperationError.CONFLICT); + } + Handoff handoff = handoffOf(stage); + if (handoff.abortAuthorized && handoff.fence == authorization.handoffFence()) { + return mutation( + authorization.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE); + } + if (handoff.fence != authorization.handoffFence() + || (!handoff.released && handoff.leaseExpiresAt.isAfter(now()))) { + throw new IllegalStateException("active or stale handoff cannot authorize abort"); + } + handoff.released = false; + handoff.abortAuthorized = true; + return mutation( + authorization.operationKey(), ObjectMutationOutcome.APPLIED, ObjectOperationError.NONE); + } + + // ---- scan maintenance --------------------------------------------------------------------- + + @Override + public synchronized ObjectScanReadReceipt transferForScan( + ObjectScanReadRequest request, ObjectContentConsumer consumer) { + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + if (!stage.version.equals(request.exactVersion())) { + throw new IllegalArgumentException("scan exact version conflicts"); + } + if (!stage.integrityVerified || stage.scanState != ObjectScanState.PENDING) { + throw new IllegalStateException("staged object is not awaiting scan"); + } + if (stage.phase == Phase.ABORTED) { + throw new IllegalStateException("staged operation was aborted"); + } + deliver(stage, request.range(), request.budget(), request.cancellation(), consumer); + boolean full = + request.range().offset() == 0 && request.range().length() == stage.content.length; + return new ObjectScanReadReceipt( + request.stageHandle(), + request.exactVersion(), + request.range(), + request.range().length(), + full ? ObjectDigestVerification.FULL_CONTENT : ObjectDigestVerification.NONE); + } + + @Override + public synchronized ObjectMutationReceipt recordScanVerdict(ObjectScanVerdictRequest request) { + Operation stage = stageOf(request.operationKey(), request.stageHandle()); + if (!stage.version.equals(request.exactVersion())) { + throw new IllegalArgumentException("scan exact version conflicts"); + } + if (stage.verdict != null) { + if (stage.verdict.equals( + new Verdict( + request.scanOperationId(), request.scannerPolicyRevision(), request.verdict()))) { + return mutation( + request.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE); + } + throw new IllegalArgumentException("a different scanner verdict is already recorded"); + } + if (!stage.integrityVerified || stage.scanState != ObjectScanState.PENDING) { + throw new IllegalStateException("staged object is not awaiting a scanner verdict"); + } + stage.verdict = + new Verdict(request.scanOperationId(), request.scannerPolicyRevision(), request.verdict()); + stage.scanState = request.verdict(); + if (stage.phase == Phase.SCAN_PENDING) { + // An aborted stage stays aborted whatever the scanner says afterwards. + stage.phase = + request.verdict() == ObjectScanState.CLEAN ? Phase.SCAN_CLEAN : Phase.QUARANTINED; + } + return mutation( + request.operationKey(), ObjectMutationOutcome.APPLIED, ObjectOperationError.NONE); + } + + // ---- internals ---------------------------------------------------------------------------- + + private Route route(ObjectDestinationId destination) { + Route route = routesByDestination.get(destination); + if (route == null) { + throw new IllegalArgumentException("object destination is not configured"); + } + return route; + } + + private Route routeOf(ObjectReference reference) { + Route route = routesByToken.get(reference.canonicalText().split("\\.", -1)[1]); + if (route == null) { + throw new IllegalArgumentException("object reference route is not configured"); + } + return route; + } + + private Operation stageOf(ObjectOperationKey key, ObjectStageHandle handle) { + Operation stage = route(key.destination()).stages.get(handle); + if (stage == null) { + throw new IllegalArgumentException("staged object is absent"); + } + if (!stage.key.equals(key)) { + throw new IllegalArgumentException("staged object operation conflicts"); + } + return stage; + } + + private Handoff handoffOf(Operation stage) { + Handoff handoff = route(stage.key.destination()).handoffs.get(stage.stageHandle); + if (handoff == null) { + throw new IllegalStateException("publication handoff is absent"); + } + return handoff; + } + + private Instant now() { + return clock.instant(); + } + + private ObjectPublishReceipt publishReceipt( + Route route, Operation operation, ObjectMutationOutcome outcome) { + return new ObjectPublishReceipt( + operation.key, + new RequestFingerprint(operation.fingerprint), + operation.reference, + operation.version, + operation.intent.contentIdentity(), + operation.intent.mediaType(), + outcome, + route.references.get(operation.reference).publishedAt, + CAPABILITY_REVISION); + } + + private static ObjectStageReceipt stageReceipt(Operation stage, ObjectMutationOutcome outcome) { + return new ObjectStageReceipt( + stage.key, stage.stageHandle, stage.version, stage.intent.contentIdentity(), outcome); + } + + private static ObjectHandoffReceipt handoffReceipt( + Operation stage, Handoff handoff, ObjectMutationOutcome outcome) { + return new ObjectHandoffReceipt( + stage.key, stage.stageHandle, handoff.fence, handoff.leaseExpiresAt, outcome); + } + + private ObjectMutationReceipt mutation( + ObjectOperationKey key, ObjectMutationOutcome outcome, ObjectOperationError error) { + return new ObjectMutationReceipt(key, outcome, error, now()); + } + + /** The producer's bytes, refused unless they are exactly the declared content. */ + private static byte[] produced( + ObjectContentProducer producer, + ObjectContentIdentity declared, + CallBudget budget, + CancellationView cancellation) { + ByteArrayOutputStream produced = new ByteArrayOutputStream(); + ObjectContentProductionContext context = + ObjectContentProductionContext.open(budget, cancellation, CHUNK_BYTES); + try { + producer.produce( + context, + ObjectChunkSink.scoped( + context, + (bytes, offset, length) -> { + if (produced.size() + (long) length > declared.exactLength()) { + throw new IllegalStateException("producer exceeded the declared length"); + } + produced.write(bytes, offset, length); + })); + } catch (ObjectContentProductionException failure) { + throw new IllegalStateException("content production failed", failure); + } finally { + context.invalidate(); + } + byte[] content = produced.toByteArray(); + if (!identity(content).equals(declared)) { + throw new IllegalStateException("produced content conflicts with declared identity"); + } + return content; + } + + private static void deliver( + Operation operation, + ObjectReadRange range, + CallBudget budget, + CancellationView cancellation, + ObjectContentConsumer consumer) { + if (range.endExclusive() > operation.content.length) { + throw new IllegalArgumentException("range exceeds the object length"); + } + ObjectContentReadContext context = + ObjectContentReadContext.open( + budget, + cancellation, + CHUNK_BYTES, + operation.intent.contentIdentity(), + operation.version, + range); + int end = (int) range.endExclusive(); + int[] position = {(int) range.offset()}; + ObjectChunkSource source = + ObjectChunkSource.scoped( + context, + (destination, offset, length) -> { + if (position[0] >= end) { + return ObjectChunkSource.EOF; + } + int count = Math.min(length, end - position[0]); + System.arraycopy(operation.content, position[0], destination, offset, count); + position[0] += count; + return count; + }); + try { + consumer.consume(context, source); + } catch (ObjectContentConsumptionException | RuntimeException failure) { + throw new IllegalStateException("bounded content consumption failed", failure); + } finally { + context.invalidate(); + } + if (position[0] != end) { + throw new IllegalStateException("consumer did not read the exact requested range"); + } + } + + private static ObjectContentIdentity identity(byte[] content) { + return new ObjectContentIdentity(content.length, ObjectDigest.sha256(content)); + } + + private static String hex(String seed, int length) { + return ObjectStorageIdentities.hex(seed, length); + } + + private enum Phase { + STAGED(ObjectPublicationState.STAGED), + VERIFIED(ObjectPublicationState.VERIFIED), + SCAN_PENDING(ObjectPublicationState.VERIFIED), + SCAN_CLEAN(ObjectPublicationState.VERIFIED), + PUBLISHED(ObjectPublicationState.PUBLISHED), + ABORTED(ObjectPublicationState.ABORTED), + QUARANTINED(ObjectPublicationState.QUARANTINED); + + private final ObjectPublicationState state; + + Phase(ObjectPublicationState state) { + this.state = state; + } + } + + private record Intent( + String kind, + ObjectMediaType mediaType, + ObjectContentIdentity contentIdentity, + ObjectPublicationRequirement publicationRequirement, + ObjectRetentionRequirement retentionRequirement, + ObjectEncryptionRequirement encryptionRequirement) {} + + private record Verdict( + ObjectOperationId scanOperationId, String policyRevision, ObjectScanState verdict) {} + + private static final class Operation { + private final ObjectOperationKey key; + private final Intent intent; + private final String fingerprint; + private final String objectId; + private final ObjectVersionToken version; + private final ObjectReference reference; + private byte[] content = new byte[0]; + private Phase phase = Phase.STAGED; + private ObjectStageHandle stageHandle; + private boolean integrityVerified; + private ObjectScanState scanState = ObjectScanState.NOT_REQUIRED; + private Verdict verdict; + + private Operation( + ObjectOperationKey key, + Intent intent, + String fingerprint, + String objectId, + ObjectVersionToken version, + ObjectReference reference) { + this.key = key; + this.intent = intent; + this.fingerprint = fingerprint; + this.objectId = objectId; + this.version = version; + this.reference = reference; + } + } + + private static final class Published { + private final Operation operation; + private final Instant publishedAt; + private boolean retired; + + private Published(Operation operation, Instant publishedAt) { + this.operation = operation; + this.publishedAt = publishedAt; + } + } + + private static final class Handoff { + private final long fence; + private final String claimant; + private Instant leaseExpiresAt; + private boolean released; + private boolean abortAuthorized; + + private Handoff(long fence, String claimant, Instant leaseExpiresAt) { + this.fence = fence; + this.claimant = claimant; + this.leaseExpiresAt = leaseExpiresAt; + } + + private boolean active(Instant now) { + return !released && !abortAuthorized && leaseExpiresAt.isAfter(now); + } + + private boolean heldBy(long expectedFence, String expectedClaimant, Instant now) { + return active(now) && fence == expectedFence && claimant.equals(expectedClaimant); + } + + private void requireOwner(long expectedFence, String expectedClaimant, Instant now) { + if (!heldBy(expectedFence, expectedClaimant, now)) { + throw new IllegalStateException("publication handoff owner/fence is stale"); + } + } + } + + private static final class Route { + private final ObjectStorageDestinationPolicy destination; + private final String token; + private final Map operations = new HashMap<>(); + private final Map references = new HashMap<>(); + private final Map stages = new HashMap<>(); + private final Map handoffs = new HashMap<>(); + + private Route(ObjectStorageDestinationPolicy destination, String token) { + this.destination = destination; + this.token = token; + } + + private void requirePolicy( + String refusal, + ObjectPublicationRequirement publication, + ObjectRetentionRequirement retention, + ObjectEncryptionRequirement encryption, + Set capabilities, + ObjectContentIdentity content) { + if (publication != destination.publicationRequirement() + || retention != destination.retentionRequirement() + || encryption != destination.encryptionRequirement() + || !destination.capabilityRequirements().containsAll(capabilities) + || content.exactLength() > destination.maximumObjectBytes()) { + throw new IllegalArgumentException(refusal); + } + } + + private Operation newOperation(ObjectOperationKey key, Intent intent) { + String fingerprint = Sha256.ofUtf8(key + "|" + intent).hex(); + String objectId = hex(token + ":" + fingerprint, 26); + Operation operation = + new Operation( + key, + intent, + fingerprint, + objectId, + ObjectVersionToken.parse( + ObjectStorageIdentities.canonical("osv1", token, hex("version:" + objectId, 26))), + ObjectReference.parse(ObjectStorageIdentities.canonical("osr1", token, objectId))); + operations.put(key, operation); + return operation; + } + + private void publish(Operation operation, Instant now) { + references.put(operation.reference, new Published(operation, now)); + } + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ManagedObjectStoragePortContract.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ManagedObjectStoragePortContract.java new file mode 100644 index 00000000..d41f980d --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ManagedObjectStoragePortContract.java @@ -0,0 +1,518 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.identity.ObjectReference; +import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; +import dev.caskeleton.application.objectstorage.model.ObjectDescriptor; +import dev.caskeleton.application.objectstorage.model.ObjectDigestVerification; +import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; +import dev.caskeleton.application.objectstorage.model.ObjectMutationReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectOperationError; +import dev.caskeleton.application.objectstorage.model.ObjectOperationResolution; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationState; +import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectReadRange; +import dev.caskeleton.application.objectstorage.model.ObjectReadReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectScanState; +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectRetirementPort; +import dev.caskeleton.application.objectstorage.port.ObjectTransferPort; +import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; +import dev.caskeleton.application.objectstorage.request.ObjectReadRequest; +import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What the managed publication path promises: publish once, read the published reference back, + * resolve the operation, retire the reference. Run against {@link InMemoryObjectStorage} and the + * adapter on its local-dev provider (capability criterion 5, docs/manual/10-capabilities.md). + * + *

The destination is an integrity-verified one (no scan gate). Every test starts from an empty + * store. + */ +public abstract class ManagedObjectStoragePortContract extends ObjectStoragePortContractSupport { + + /** The single-call publication port under test. */ + protected abstract ManagedObjectPublicationPort publication(); + + /** The inspection port of the same storage. */ + protected abstract ObjectInspectionPort inspection(); + + /** The transfer port of the same storage. */ + protected abstract ObjectTransferPort transfer(); + + /** The operation resolution port of the same storage. */ + protected abstract ObjectOperationResolutionPort resolution(); + + /** The retirement port of the same storage. */ + protected abstract ObjectRetirementPort retirement(); + + @Test + @DisplayName("게시한 객체는 선언한 내용 식별자와 media type으로 조회된다") + void aPublishedObjectInspectsWithItsDeclaredIdentity() { + // given + byte[] content = content(200, 1); + ObjectPublishReceipt published = publish("publish-a", content); + + // when + Optional descriptor = inspection().inspect(published.reference()); + + // then + assertThat(descriptor) + .get() + .satisfies( + found -> { + assertThat(found.contentIdentity()).isEqualTo(identityOf(content)); + assertThat(found.declaredMediaType()).isEqualTo(MEDIA_TYPE); + assertThat(found.exactVersion()).isEqualTo(published.exactVersion()); + assertThat(found.publicationState()).isEqualTo(ObjectPublicationState.PUBLISHED); + assertThat(found.scanState()).isEqualTo(ObjectScanState.NOT_REQUIRED); + }); + } + + @Test + @DisplayName("처음 게시하면 APPLIED다") + void aFirstPublicationIsApplied() { + // given + byte[] content = content(200, 21); + + // when + ObjectPublishReceipt published = + publication().publish(publishRequest(key("publish-first"), content), producing(content)); + + // then + assertThat(published.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(published.contentIdentity()).isEqualTo(identityOf(content)); + } + + @Test + @DisplayName("게시한 객체 전체를 전송하면 같은 바이트와 전체 digest 검증을 받는다") + void transferringTheWholeObjectDeliversItsBytes() { + // given + byte[] content = content(200, 2); + ObjectPublishReceipt published = publish("transfer-whole", content); + Collected collected = new Collected(); + + // when + ObjectReadReceipt read = + transfer() + .transfer( + read( + published.reference(), + Optional.of(published.exactVersion()), + 0, + content.length), + collected); + + // then + assertThat(collected.bytes()).containsExactly(content); + assertThat(read.exactVersion()).isEqualTo(published.exactVersion()); + assertThat(read.digestVerification()).isEqualTo(ObjectDigestVerification.FULL_CONTENT); + } + + @Test + @DisplayName("범위를 전송하면 그 범위의 바이트만 받고 전체 digest 검증은 없다") + void transferringARangeDeliversOnlyThatRange() { + // given + byte[] content = content(200, 3); + ObjectPublishReceipt published = publish("transfer-range", content); + Collected collected = new Collected(); + + // when + ObjectReadReceipt read = + transfer().transfer(read(published.reference(), Optional.empty(), 40, 50), collected); + + // then + assertThat(collected.bytes()).containsExactly(java.util.Arrays.copyOfRange(content, 40, 90)); + assertThat(read.deliveredRange()).isEqualTo(ObjectReadRange.of(40, 50)); + assertThat(read.digestVerification()).isEqualTo(ObjectDigestVerification.NONE); + } + + @Test + @DisplayName("같은 operation key로 다시 게시하면 producer를 부르지 않고 같은 reference를 REPLAYED로 돌려준다") + void republishingTheSameKeyReplaysWithoutProducing() { + // given + byte[] content = content(200, 4); + ObjectOperationKey key = key("publish-replay"); + ObjectPublishReceipt first = + publication().publish(publishRequest(key, content), producing(content)); + AtomicBoolean produced = new AtomicBoolean(); + + // when + ObjectPublishReceipt replay = + publication().publish(publishRequest(key, content), recording(produced)); + + // then + assertThat(replay.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + assertThat(replay.reference()).isEqualTo(first.reference()); + assertThat(replay.exactVersion()).isEqualTo(first.exactVersion()); + assertThat(produced).as("a replay must not produce the bytes again").isFalse(); + } + + @Test + @DisplayName("같은 operation key에 다른 내용을 게시하면 거절한다") + void aDifferentIntentUnderTheSameKeyIsRefused() { + // given + ObjectOperationKey key = key("publish-conflict"); + byte[] original = content(200, 5); + publication().publish(publishRequest(key, original), producing(original)); + byte[] other = content(200, 6); + + // when + Throwable refused = + catchThrowable(() -> publication().publish(publishRequest(key, other), producing(other))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("capability 요구만 다른 같은 게시는 같은 의도로 보고 REPLAYED다") + void aCapabilityOnlyDifferenceIsTheSameIntent() { + // given + ObjectOperationKey key = key("publish-capabilities"); + byte[] content = content(200, 22); + ObjectPublishReceipt first = + publication().publish(publishRequest(key, content), producing(content)); + ObjectPublishRequest withoutCapabilities = + new ObjectPublishRequest( + key, + MEDIA_TYPE, + identityOf(content), + destination().publicationRequirement(), + destination().retentionRequirement(), + destination().encryptionRequirement(), + Set.of(), + budget(), + CancellationView.never()); + + // when + ObjectPublishReceipt again = publication().publish(withoutCapabilities, producing(content)); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + assertThat(again.reference()).isEqualTo(first.reference()); + } + + @Test + @DisplayName("destination 한도보다 큰 내용은 게시를 거절한다") + void contentLargerThanTheDestinationAllowsIsRefused() { + // given + byte[] content = content(Math.toIntExact(destination().maximumObjectBytes() + 1), 7); + + // when + Throwable refused = + catchThrowable( + () -> + publication() + .publish( + publishRequest(key("publish-too-large"), content), producing(content))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("destination 한도와 같은 크기는 게시된다") + void contentAtTheDestinationLimitPublishes() { + // given + byte[] content = content(Math.toIntExact(destination().maximumObjectBytes()), 23); + + // when + ObjectPublishReceipt published = + publication().publish(publishRequest(key("publish-at-limit"), content), producing(content)); + + // then + assertThat(published.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(published.contentIdentity()).isEqualTo(identityOf(content)); + } + + @Test + @DisplayName("선언과 다른 바이트를 만들면 게시를 거절한다") + void producedBytesThatDifferFromTheDeclarationAreRefused() { + // given + byte[] declared = content(200, 8); + byte[] produced = content(200, 9); + + // when + Throwable failed = + catchThrowable( + () -> + publication() + .publish( + publishRequest(key("publish-mismatch"), declared), producing(produced))); + + // then + assertThat(failed) + .as("the port refuses; which unchecked exception is the implementation's") + .isInstanceOf(RuntimeException.class) + .isNotInstanceOf(NullPointerException.class); + } + + @Test + @DisplayName("다른 바이트로 실패한 게시는 복구 조회에서 진행 중이고 게시된 reference가 없다") + void aFailedPublicationResolvesInProgress() { + // given + ObjectOperationKey key = key("publish-failed"); + byte[] declared = content(200, 24); + failedAttempt( + () -> publication().publish(publishRequest(key, declared), producing(content(200, 25)))); + + // when + ObjectOperationResolution resolution = resolution().resolve(key); + + // then + assertThat(resolution.state()).isEqualTo(ObjectPublicationState.STAGED); + assertThat(resolution.outcome()).isEqualTo(ObjectMutationOutcome.INDETERMINATE); + assertThat(resolution.error()).isEqualTo(ObjectOperationError.NONE); + assertThat(resolution.publishedReference()).isEmpty(); + } + + @Test + @DisplayName("실패한 게시를 같은 key와 바른 바이트로 다시 하면 이번 호출이 게시해 APPLIED다") + void retryingAFailedPublicationPublishesIt() { + // given + ObjectOperationKey key = key("publish-retry"); + byte[] content = content(200, 26); + failedAttempt( + () -> publication().publish(publishRequest(key, content), producing(content(200, 27)))); + + // when + ObjectPublishReceipt retried = + publication().publish(publishRequest(key, content), producing(content)); + + // then + assertThat(retried.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(inspection().inspect(retried.reference())).isPresent(); + } + + @Test + @DisplayName("기대한 version이 다르면 전송을 거절한다") + void aVersionPreconditionThatDoesNotMatchRefusesTheTransfer() { + // given + byte[] content = content(200, 10); + ObjectPublishReceipt published = publish("version-a", content); + ObjectVersionToken other = publish("version-b", content(200, 11)).exactVersion(); + + // when + Throwable refused = + catchThrowable( + () -> + transfer() + .transfer( + read(published.reference(), Optional.of(other), 0, content.length), + new Collected())); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("게시되지 않은 reference는 조회가 비어 있다") + void anUnpublishedReferenceInspectsEmpty() { + // given + ObjectReference absent = absentSibling(publish("absent-inspect", content(200, 12)).reference()); + + // when + Optional descriptor = inspection().inspect(absent); + + // then + assertThat(descriptor).isEmpty(); + } + + @Test + @DisplayName("게시되지 않은 reference는 전송을 거절한다") + void anUnpublishedReferenceRefusesTransfer() { + // given + ObjectReference absent = + absentSibling(publish("absent-transfer", content(200, 13)).reference()); + + // when + Throwable refused = + catchThrowable( + () -> transfer().transfer(read(absent, Optional.empty(), 0, 10), new Collected())); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("범위를 끝까지 읽지 않고 돌아온 consumer는 전송을 거절한다") + void aConsumerThatStopsEarlyIsRefused() { + // given + byte[] content = content(200, 28); + ObjectPublishReceipt published = publish("transfer-early-stop", content); + + // when + Throwable refused = + catchThrowable( + () -> + transfer() + .transfer( + read(published.reference(), Optional.empty(), 0, content.length), + readingOneChunk())); + + // then + assertThat(refused) + .as( + "a consumer must read the exact range; which unchecked exception is the implementation's") + .isInstanceOf(RuntimeException.class) + .isNotInstanceOf(NullPointerException.class); + } + + @Test + @DisplayName("모르는 operation key를 복구 조회하면 NOT_FOUND로 거절한다") + void resolvingAnUnknownKeyReportsNotFound() { + // when + ObjectOperationResolution resolution = resolution().resolve(key("never-seen")); + + // then + assertThat(resolution.outcome()).isEqualTo(ObjectMutationOutcome.REJECTED); + assertThat(resolution.error()).isEqualTo(ObjectOperationError.NOT_FOUND); + assertThat(resolution.publishedReference()).isEmpty(); + } + + @Test + @DisplayName("게시한 operation key를 복구 조회하면 PUBLISHED와 그 reference를 돌려준다") + void resolvingAPublishedKeyReturnsItsReference() { + // given + ObjectOperationKey key = key("resolve-published"); + byte[] content = content(200, 14); + ObjectPublishReceipt published = + publication().publish(publishRequest(key, content), producing(content)); + + // when + ObjectOperationResolution resolution = resolution().resolve(key); + + // then + assertThat(resolution.state()).isEqualTo(ObjectPublicationState.PUBLISHED); + assertThat(resolution.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(resolution.publishedReference()).contains(published.reference()); + } + + @Test + @DisplayName("회수하면 APPLIED이고 그 reference는 더 이상 조회되지 않는다") + void retiringAReferenceHidesItFromInspection() { + // given + ObjectPublishReceipt published = publish("retire-inspect", content(200, 15)); + + // when + ObjectMutationReceipt retired = + retirement().retire(retire(published, published.exactVersion())); + + // then + assertThat(retired.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(inspection().inspect(published.reference())).isEmpty(); + } + + @Test + @DisplayName("회수한 reference는 전송을 거절한다") + void aRetiredReferenceRefusesTransfer() { + // given + byte[] content = content(200, 16); + ObjectPublishReceipt published = publish("retire-transfer", content); + retirement().retire(retire(published, published.exactVersion())); + + // when + Throwable refused = + catchThrowable( + () -> + transfer() + .transfer( + read(published.reference(), Optional.empty(), 0, content.length), + new Collected())); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("같은 회수를 다시 하면 REPLAYED다") + void retiringAgainReplays() { + // given + ObjectPublishReceipt published = publish("retire-replay", content(200, 17)); + retirement().retire(retire(published, published.exactVersion())); + + // when + ObjectMutationReceipt again = retirement().retire(retire(published, published.exactVersion())); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + assertThat(again.error()).isEqualTo(ObjectOperationError.NONE); + } + + @Test + @DisplayName("다른 version으로 회수하면 CONFLICT로 거절하고 객체는 그대로 조회된다") + void retiringWithAnotherVersionConflictsAndKeepsTheObject() { + // given + ObjectPublishReceipt published = publish("retire-conflict", content(200, 18)); + ObjectVersionToken other = publish("retire-other", content(200, 19)).exactVersion(); + + // when + ObjectMutationReceipt refused = retirement().retire(retire(published, other)); + + // then + assertThat(refused.outcome()).isEqualTo(ObjectMutationOutcome.REJECTED); + assertThat(refused.error()).isEqualTo(ObjectOperationError.CONFLICT); + assertThat(inspection().inspect(published.reference())).isPresent(); + } + + @Test + @DisplayName("게시되지 않은 reference는 회수를 거절한다") + void retiringAnUnpublishedReferenceIsRefused() { + // given + ObjectPublishReceipt published = publish("retire-absent", content(200, 20)); + ObjectReference absent = absentSibling(published.reference()); + + // when + Throwable refused = + catchThrowable( + () -> + retirement() + .retire( + new ObjectRetireRequest( + key("retire-absent-op"), + absent, + published.exactVersion(), + budget(), + CancellationView.never()))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + private ObjectPublishReceipt publish(String operation, byte[] content) { + return publication().publish(publishRequest(key(operation), content), producing(content)); + } + + private static ObjectReadRequest read( + ObjectReference reference, Optional version, long offset, long length) { + return new ObjectReadRequest( + reference, + version, + ObjectReadRange.of(offset, length), + ObjectDigestVerification.FULL_CONTENT, + length, + budget(), + CancellationView.never()); + } + + private ObjectRetireRequest retire(ObjectPublishReceipt published, ObjectVersionToken version) { + return new ObjectRetireRequest( + key("retire-of-" + published.operationKey().operationId().value()), + published.reference(), + version, + budget(), + CancellationView.never()); + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectScanMaintenancePortContract.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectScanMaintenancePortContract.java new file mode 100644 index 00000000..9d765e4c --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectScanMaintenancePortContract.java @@ -0,0 +1,359 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.model.ObjectDescriptor; +import dev.caskeleton.application.objectstorage.model.ObjectDigestVerification; +import dev.caskeleton.application.objectstorage.model.ObjectHandoffReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; +import dev.caskeleton.application.objectstorage.model.ObjectMutationReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectOperationResolution; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationState; +import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectReadRange; +import dev.caskeleton.application.objectstorage.model.ObjectScanReadReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectScanState; +import dev.caskeleton.application.objectstorage.model.ObjectStageReceipt; +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.ObjectScanMaintenancePort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.request.ObjectAbortAuthorization; +import dev.caskeleton.application.objectstorage.request.ObjectAbortRequest; +import dev.caskeleton.application.objectstorage.request.ObjectFinalizeRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffReleaseRequest; +import dev.caskeleton.application.objectstorage.request.ObjectScanReadRequest; +import dev.caskeleton.application.objectstorage.request.ObjectScanVerdictRequest; +import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; +import java.time.Instant; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What a scan-gated destination promises: nothing publishes until a scanner has read the exact + * staged bytes and recorded CLEAN, and a managed single-call publish never reaches it. Run against + * {@link InMemoryObjectStorage} and the adapter on its local-dev provider (capability criterion 5). + * + *

{@link #destination()} is a scan-gated destination. Every test starts from an empty store. + */ +public abstract class ObjectScanMaintenancePortContract extends ObjectStoragePortContractSupport { + + private static final String CLAIMANT = "worker-a"; + private static final String SCANNER_POLICY = "scanner-v1"; + + /** The scanner-workflow port under test. */ + protected abstract ObjectScanMaintenancePort scan(); + + /** The staged publication port of the same storage. */ + protected abstract StagedObjectPublicationPort staged(); + + /** The publication handoff port of the same storage. */ + protected abstract ObjectPublicationHandoffPort handoff(); + + /** The single-call publication port of the same storage. */ + protected abstract ManagedObjectPublicationPort publication(); + + /** The inspection port of the same storage. */ + protected abstract ObjectInspectionPort inspection(); + + /** The operation resolution port of the same storage. */ + protected abstract ObjectOperationResolutionPort resolution(); + + @Test + @DisplayName("scan이 필요한 destination에는 한 번 호출 게시를 거절한다") + void aScanGatedDestinationRefusesManagedPublication() { + // given + byte[] content = content(200, 61); + + // when + Throwable refused = + catchThrowable( + () -> + publication() + .publish(publishRequest(key("managed-refused"), content), producing(content))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("검증하지 않은 stage는 scanner가 읽지 못한다") + void anUnverifiedStageIsNotReadableForScan() { + // given + ObjectOperationKey key = key("scan-unverified"); + byte[] content = content(200, 62); + ObjectStageReceipt stage = staged().stage(stageRequest(key, content), producing(content)); + + // when + Throwable refused = + catchThrowable( + () -> scan().transferForScan(scanRead(key, stage, 0, content.length), new Collected())); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("검증한 stage는 scanner가 같은 바이트를 전체 digest 검증과 함께 읽는다") + void aVerifiedStageIsReadableForScan() { + // given + ObjectOperationKey key = key("scan-read"); + byte[] content = content(200, 63); + ObjectStageReceipt stage = verifiedStage(key, content); + Collected collected = new Collected(); + + // when + ObjectScanReadReceipt read = + scan().transferForScan(scanRead(key, stage, 0, content.length), collected); + + // then + assertThat(collected.bytes()).containsExactly(content); + assertThat(read.digestVerification()).isEqualTo(ObjectDigestVerification.FULL_CONTENT); + } + + @Test + @DisplayName("범위를 끝까지 읽지 않고 돌아온 scanner는 거절한다") + void aScannerThatStopsEarlyIsRefused() { + // given + ObjectOperationKey key = key("scan-early-stop"); + byte[] content = content(200, 68); + ObjectStageReceipt stage = verifiedStage(key, content); + + // when + Throwable refused = + catchThrowable( + () -> + scan().transferForScan(scanRead(key, stage, 0, content.length), readingOneChunk())); + + // then + assertThat(refused) + .as( + "a scanner must read the exact range; which unchecked exception is the implementation's") + .isInstanceOf(RuntimeException.class) + .isNotInstanceOf(NullPointerException.class); + } + + @Test + @DisplayName("CLEAN 판정을 기록하면 APPLIED다") + void recordingACleanVerdictIsApplied() { + // given + ObjectOperationKey key = key("scan-clean-record"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 69)); + + // when + ObjectMutationReceipt verdict = + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.CLEAN)); + + // then + assertThat(verdict.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + } + + @Test + @DisplayName("CLEAN 판정 뒤 finalize하면 게시되고 조회에 CLEAN이 보인다") + void aCleanVerdictLetsTheStagePublish() { + // given + ObjectOperationKey key = key("scan-clean"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 64)); + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.CLEAN)); + ObjectHandoffReceipt claim = claim(key, stage); + + // when + ObjectPublishReceipt published = staged().finalizePublication(finalize(key, stage, claim)); + + // then + assertThat(published.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(inspection().inspect(published.reference())) + .get() + .extracting(ObjectDescriptor::scanState) + .isEqualTo(ObjectScanState.CLEAN); + } + + @Test + @DisplayName("판정 없이는 claim이 있어도 finalize를 거절한다") + void finalizeWithoutAVerdictIsRefused() { + // given + ObjectOperationKey key = key("scan-no-verdict"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 65)); + ObjectHandoffReceipt claim = claim(key, stage); + + // when + Throwable refused = + catchThrowable(() -> staged().finalizePublication(finalize(key, stage, claim))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("MALICIOUS 판정은 stage를 격리한다") + void aMaliciousVerdictQuarantinesTheStage() { + // given + ObjectOperationKey key = key("scan-malicious"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 66)); + + // when + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.MALICIOUS)); + + // then + ObjectOperationResolution resolution = resolution().resolve(key); + assertThat(resolution.state()).isEqualTo(ObjectPublicationState.QUARANTINED); + assertThat(resolution.publishedReference()).isEmpty(); + } + + @Test + @DisplayName("MALICIOUS 판정 뒤에는 finalize를 거절한다") + void aMaliciousStageCannotFinalize() { + // given + ObjectOperationKey key = key("scan-malicious-finalize"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 70)); + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.MALICIOUS)); + ObjectHandoffReceipt claim = claim(key, stage); + + // when + Throwable refused = + catchThrowable(() -> staged().finalizePublication(finalize(key, stage, claim))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("같은 판정을 다시 기록하면 REPLAYED다") + void theSameVerdictReplays() { + // given + ObjectOperationKey key = key("scan-verdict-replay"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 67)); + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.CLEAN)); + + // when + ObjectMutationReceipt again = + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.CLEAN)); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + } + + @Test + @DisplayName("기록한 판정과 다른 판정은 거절한다") + void aRecordedVerdictCannotChange() { + // given + ObjectOperationKey key = key("scan-verdict-change"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 71)); + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.CLEAN)); + + // when + Throwable refused = + catchThrowable( + () -> scan().recordScanVerdict(verdict(key, stage, ObjectScanState.MALICIOUS))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("중단한 stage에 판정을 기록해도 ABORTED로 남는다") + void aVerdictOnAnAbortedStageLeavesItAborted() { + // given + ObjectOperationKey key = key("scan-aborted"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 72)); + abortReleased(key, stage); + + // when + scan().recordScanVerdict(verdict(key, stage, ObjectScanState.CLEAN)); + + // then + assertThat(resolution().resolve(key).state()).isEqualTo(ObjectPublicationState.ABORTED); + } + + private void abortReleased(ObjectOperationKey key, ObjectStageReceipt stage) { + ObjectHandoffReceipt claim = claim(key, stage); + handoff() + .releaseClaim( + new ObjectHandoffReleaseRequest( + key, + stage.stageHandle(), + claim.fence(), + CLAIMANT, + budget(), + CancellationView.never())); + ObjectAbortAuthorization authorization = + new ObjectAbortAuthorization( + key, stage.stageHandle(), stage.exactVersion(), claim.fence(), Instant.now()); + handoff().authorizeAbort(authorization); + staged() + .abort( + new ObjectAbortRequest( + key, stage.stageHandle(), authorization, budget(), CancellationView.never())); + } + + private ObjectStageReceipt verifiedStage(ObjectOperationKey key, byte[] content) { + ObjectStageReceipt stage = staged().stage(stageRequest(key, content), producing(content)); + staged() + .verifyIntegrity( + new ObjectVerifyRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + stage.contentIdentity(), + budget(), + CancellationView.never())); + return stage; + } + + private ObjectHandoffReceipt claim(ObjectOperationKey key, ObjectStageReceipt stage) { + return handoff() + .claimForPublication( + new ObjectHandoffClaimRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + CLAIMANT, + LEASE, + budget(), + CancellationView.never())); + } + + private ObjectFinalizeRequest finalize( + ObjectOperationKey key, ObjectStageReceipt stage, ObjectHandoffReceipt claim) { + return new ObjectFinalizeRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + destination().publicationRequirement(), + claim.fence(), + CLAIMANT, + budget(), + CancellationView.never()); + } + + private static ObjectScanReadRequest scanRead( + ObjectOperationKey key, ObjectStageReceipt stage, long offset, long length) { + return new ObjectScanReadRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + ObjectReadRange.of(offset, length), + length, + budget(), + CancellationView.never()); + } + + private static ObjectScanVerdictRequest verdict( + ObjectOperationKey key, ObjectStageReceipt stage, ObjectScanState verdict) { + return new ObjectScanVerdictRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + ObjectOperationId.of("scan-of-" + key.operationId().value()), + SCANNER_POLICY, + verdict, + Instant.now()); + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageDestinationPolicy.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageDestinationPolicy.java new file mode 100644 index 00000000..84a6091d --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageDestinationPolicy.java @@ -0,0 +1,60 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; +import dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectEncryptionRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationRequirement; +import dev.caskeleton.application.objectstorage.model.ObjectRetentionRequirement; +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; + +/** + * One destination as the port contracts see it: its id and the policy every request to it must + * satisfy. An implementation under test describes the destination it is configured with; the + * contracts build their requests from this, and {@link InMemoryObjectStorage} enforces it. + */ +public record ObjectStorageDestinationPolicy( + ObjectDestinationId id, + ObjectPublicationRequirement publicationRequirement, + ObjectRetentionRequirement retentionRequirement, + ObjectEncryptionRequirement encryptionRequirement, + Set capabilityRequirements, + long maximumObjectBytes) { + + public ObjectStorageDestinationPolicy { + Objects.requireNonNull(id, "id must be non-null"); + Objects.requireNonNull(publicationRequirement, "publicationRequirement must be non-null"); + Objects.requireNonNull(retentionRequirement, "retentionRequirement must be non-null"); + Objects.requireNonNull(encryptionRequirement, "encryptionRequirement must be non-null"); + capabilityRequirements = Set.copyOf(capabilityRequirements); + if (maximumObjectBytes < 1) { + throw new IllegalArgumentException("maximumObjectBytes must be positive"); + } + } + + /** + * An integrity-verified destination: no retention, provider-managed encryption, immutable create. + */ + public static ObjectStorageDestinationPolicy integrityVerified( + String id, long maximumObjectBytes) { + return new ObjectStorageDestinationPolicy( + ObjectDestinationId.of(id), + ObjectPublicationRequirement.INTEGRITY_VERIFIED, + ObjectRetentionRequirement.NONE, + ObjectEncryptionRequirement.PROVIDER_MANAGED, + EnumSet.of(ObjectCapabilityRequirement.IMMUTABLE_CREATE), + maximumObjectBytes); + } + + /** The same destination, but publishing only after a CLEAN scanner verdict. */ + public ObjectStorageDestinationPolicy scanGated() { + return new ObjectStorageDestinationPolicy( + id, + ObjectPublicationRequirement.SCAN_CLEAN, + retentionRequirement, + encryptionRequirement, + capabilityRequirements, + maximumObjectBytes); + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageIdentities.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageIdentities.java new file mode 100644 index 00000000..1b54eeae --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStorageIdentities.java @@ -0,0 +1,24 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.shared.digest.Sha256; + +/** + * Canonical identity text for the test kit: {@code family.route.id.check}, with the check digits + * the identity types verify (the first ten hex digits of the payload's SHA-256, as {@code + * ObjectIdentitySupport} requires). Lowercase hex is valid Crockford base32 text. + */ +final class ObjectStorageIdentities { + + private ObjectStorageIdentities() {} + + /** {@code family.route.id} followed by its check digits. */ + static String canonical(String family, String route, String id) { + String payload = family + "." + route + "." + id; + return payload + "." + hex(payload, 10); + } + + /** The first {@code length} lowercase hex digits of the SHA-256 of {@code seed}. */ + static String hex(String seed, int length) { + return Sha256.ofUtf8(seed).hex().substring(0, length); + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStoragePortContractSupport.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStoragePortContractSupport.java new file mode 100644 index 00000000..f32fbff5 --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/ObjectStoragePortContractSupport.java @@ -0,0 +1,162 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import dev.caskeleton.application.objectstorage.content.CallBudget; +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.content.ObjectChunkReadException; +import dev.caskeleton.application.objectstorage.content.ObjectChunkSource; +import dev.caskeleton.application.objectstorage.content.ObjectContentConsumer; +import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; +import dev.caskeleton.application.objectstorage.content.ObjectContentReadContext; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.identity.ObjectReference; +import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; +import dev.caskeleton.application.objectstorage.model.ObjectDigest; +import dev.caskeleton.application.objectstorage.model.ObjectMediaType; +import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; +import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; +import java.io.ByteArrayOutputStream; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicBoolean; +import org.assertj.core.api.Assertions; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; + +/** + * What the object-storage port contracts share: the destination the implementation under test is + * configured with, content and its identity, and requests that satisfy that destination's policy. + * + *

A subclass describes its destination with {@link #destination()}. Chunks are 16 bytes each + * way, below the smallest chunk size an implementation accepts. + */ +public abstract class ObjectStoragePortContractSupport { + + /** The media type every contract object is published with. */ + protected static final ObjectMediaType MEDIA_TYPE = + ObjectMediaType.of("application/octet-stream"); + + /** How long a contract publication claim lasts; no contract test waits for it to run out. */ + protected static final Duration LEASE = Duration.ofMinutes(5); + + private static final int CHUNK = 16; + + /** + * The destination the implementation under test is configured with: its id and the policy it + * enforces. Contract requests satisfy it exactly. + */ + protected abstract ObjectStorageDestinationPolicy destination(); + + /** A key on the configured destination for {@code operation}. */ + protected final ObjectOperationKey key(String operation) { + return new ObjectOperationKey( + destination().id(), ObjectOperationEpoch.of("epoch-a"), ObjectOperationId.of(operation)); + } + + /** A managed publication of {@code content} that satisfies the destination policy. */ + protected final ObjectPublishRequest publishRequest(ObjectOperationKey key, byte[] content) { + ObjectStorageDestinationPolicy destination = destination(); + return new ObjectPublishRequest( + key, + MEDIA_TYPE, + identityOf(content), + destination.publicationRequirement(), + destination.retentionRequirement(), + destination.encryptionRequirement(), + destination.capabilityRequirements(), + budget(), + CancellationView.never()); + } + + /** A stage of {@code content} that satisfies the destination policy. */ + protected final ObjectStageRequest stageRequest(ObjectOperationKey key, byte[] content) { + ObjectStorageDestinationPolicy destination = destination(); + return new ObjectStageRequest( + key, + MEDIA_TYPE, + identityOf(content), + destination.publicationRequirement(), + destination.retentionRequirement(), + destination.encryptionRequirement(), + destination.capabilityRequirements(), + budget(), + CancellationView.never()); + } + + /** {@code length} bytes that differ for every {@code seed}. */ + protected static byte[] content(int length, int seed) { + byte[] content = new byte[length]; + for (int index = 0; index < length; index++) { + content[index] = (byte) (index * 31 + seed * 7); + } + return content; + } + + /** The exact length and SHA-256 of {@code content}. */ + protected static ObjectContentIdentity identityOf(byte[] content) { + return new ObjectContentIdentity(content.length, ObjectDigest.sha256(content)); + } + + /** A producer that writes {@code content} in small chunks. */ + protected static ObjectContentProducer producing(byte[] content) { + return (context, sink) -> { + for (int offset = 0; offset < content.length; offset += CHUNK) { + sink.write(content, offset, Math.min(CHUNK, content.length - offset)); + } + }; + } + + /** A producer that records whether it was called and writes nothing. */ + protected static ObjectContentProducer recording(AtomicBoolean called) { + return (context, sink) -> called.set(true); + } + + /** Runs an attempt the test needs to have failed, and stops the test if it did not. */ + protected static void failedAttempt(ThrowingCallable attempt) { + if (Assertions.catchThrowable(attempt) == null) { + throw new AssertionError("the attempt the test starts from was expected to fail"); + } + } + + /** A minute of call budget from now. */ + protected static CallBudget budget() { + return CallBudget.fromNow(Duration.ofMinutes(1)); + } + + /** + * A canonical reference on the same route as {@code published} that names no object: a different + * object id with its own check digits. + */ + protected static ObjectReference absentSibling(ObjectReference published) { + String[] parts = published.canonicalText().split("\\.", -1); + return ObjectReference.parse( + ObjectStorageIdentities.canonical( + parts[0], parts[1], ObjectStorageIdentities.hex("absent:" + parts[2], 26))); + } + + /** A consumer that reads one chunk and returns, leaving the rest of the range unread. */ + protected static ObjectContentConsumer readingOneChunk() { + return (context, source) -> source.read(new byte[CHUNK], 0, CHUNK); + } + + /** A consumer that keeps every byte it is given. */ + protected static final class Collected implements ObjectContentConsumer { + + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + + @Override + public void consume(ObjectContentReadContext context, ObjectChunkSource source) + throws ObjectChunkReadException { + byte[] buffer = new byte[CHUNK]; + for (int count = source.read(buffer, 0, buffer.length); + count != ObjectChunkSource.EOF; + count = source.read(buffer, 0, buffer.length)) { + bytes.write(buffer, 0, count); + } + } + + /** What the transfer delivered. */ + public byte[] bytes() { + return bytes.toByteArray(); + } + } +} diff --git a/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/StagedObjectPublicationPortContract.java b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/StagedObjectPublicationPortContract.java new file mode 100644 index 00000000..fd0e61ff --- /dev/null +++ b/src/application/objectstorage/src/testFixtures/java/dev/caskeleton/application/objectstorage/testkit/StagedObjectPublicationPortContract.java @@ -0,0 +1,634 @@ +package dev.caskeleton.application.objectstorage.testkit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; +import dev.caskeleton.application.objectstorage.model.ObjectHandoffReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; +import dev.caskeleton.application.objectstorage.model.ObjectMutationReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectOperationError; +import dev.caskeleton.application.objectstorage.model.ObjectOperationResolution; +import dev.caskeleton.application.objectstorage.model.ObjectPublicationState; +import dev.caskeleton.application.objectstorage.model.ObjectPublishReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectStageReceipt; +import dev.caskeleton.application.objectstorage.model.ObjectVerificationReceipt; +import dev.caskeleton.application.objectstorage.port.ObjectInspectionPort; +import dev.caskeleton.application.objectstorage.port.ObjectOperationResolutionPort; +import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; +import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.request.ObjectAbortAuthorization; +import dev.caskeleton.application.objectstorage.request.ObjectAbortRequest; +import dev.caskeleton.application.objectstorage.request.ObjectFinalizeRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffReleaseRequest; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffRenewRequest; +import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; +import java.time.Instant; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * What staged publication and its fenced handoff promise: stage, verify, claim, finalize, and the + * abort that only an authorized, unclaimed stage allows. Run against {@link InMemoryObjectStorage} + * and the adapter on its local-dev provider (capability criterion 5). + * + *

The destination is an integrity-verified one; the scan gate is {@link + * ObjectScanMaintenancePortContract}'s. Every test starts from an empty store, and no test waits + * for a claim's lease to run out. + */ +public abstract class StagedObjectPublicationPortContract extends ObjectStoragePortContractSupport { + + /** The claimant every contract claim is taken by unless a test names another. */ + protected static final String CLAIMANT = "worker-a"; + + /** The staged publication port under test. */ + protected abstract StagedObjectPublicationPort staged(); + + /** The publication handoff port of the same storage. */ + protected abstract ObjectPublicationHandoffPort handoff(); + + /** The inspection port of the same storage. */ + protected abstract ObjectInspectionPort inspection(); + + /** The operation resolution port of the same storage. */ + protected abstract ObjectOperationResolutionPort resolution(); + + @Test + @DisplayName("stage·검증·claim·finalize를 거치면 게시되고 그 reference가 조회된다") + void stageVerifyClaimAndFinalizePublishes() { + // given + ObjectOperationKey key = key("staged-publish"); + byte[] content = content(200, 31); + ObjectStageReceipt stage = verifiedStage(key, content); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + + // when + ObjectPublishReceipt published = staged().finalizePublication(finalize(key, stage, claim)); + + // then + assertThat(published.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(published.contentIdentity()).isEqualTo(identityOf(content)); + assertThat(inspection().inspect(published.reference())).isPresent(); + } + + @Test + @DisplayName("같은 operation key로 다시 stage하면 producer를 부르지 않고 같은 handle을 REPLAYED로 돌려준다") + void restagingTheSameKeyReplaysWithoutProducing() { + // given + ObjectOperationKey key = key("stage-replay"); + byte[] content = content(200, 32); + ObjectStageReceipt first = staged().stage(stageRequest(key, content), producing(content)); + AtomicBoolean produced = new AtomicBoolean(); + + // when + ObjectStageReceipt replay = staged().stage(stageRequest(key, content), recording(produced)); + + // then + assertThat(replay.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + assertThat(replay.stageHandle()).isEqualTo(first.stageHandle()); + assertThat(replay.exactVersion()).isEqualTo(first.exactVersion()); + assertThat(produced).as("a replay must not produce the bytes again").isFalse(); + } + + @Test + @DisplayName("같은 operation key에 다른 내용을 stage하면 거절한다") + void aDifferentStageUnderTheSameKeyIsRefused() { + // given + ObjectOperationKey key = key("stage-conflict"); + byte[] original = content(200, 33); + staged().stage(stageRequest(key, original), producing(original)); + byte[] other = content(200, 34); + + // when + Throwable refused = + catchThrowable(() -> staged().stage(stageRequest(key, other), producing(other))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("선언과 다른 바이트를 stage하면 거절한다") + void stagedBytesThatDifferFromTheDeclarationAreRefused() { + // given + byte[] declared = content(200, 35); + byte[] produced = content(200, 36); + + // when + Throwable failed = + catchThrowable( + () -> + staged().stage(stageRequest(key("stage-mismatch"), declared), producing(produced))); + + // then + assertThat(failed) + .as("the port refuses; which unchecked exception is the implementation's") + .isInstanceOf(RuntimeException.class) + .isNotInstanceOf(NullPointerException.class); + } + + @Test + @DisplayName("다른 바이트로 실패한 stage는 복구 조회에서 진행 중이다") + void aFailedStageResolvesInProgress() { + // given + ObjectOperationKey key = key("stage-failed"); + byte[] declared = content(200, 54); + failedAttempt(() -> staged().stage(stageRequest(key, declared), producing(content(200, 55)))); + + // when + ObjectOperationResolution resolution = resolution().resolve(key); + + // then + assertThat(resolution.state()).isEqualTo(ObjectPublicationState.STAGED); + assertThat(resolution.outcome()).isEqualTo(ObjectMutationOutcome.INDETERMINATE); + assertThat(resolution.error()).isEqualTo(ObjectOperationError.NONE); + assertThat(resolution.publishedReference()).isEmpty(); + } + + @Test + @DisplayName("실패한 stage를 같은 key와 바른 바이트로 다시 하면 이번 호출이 stage해 APPLIED다") + void retryingAFailedStageStagesIt() { + // given + ObjectOperationKey key = key("stage-retry"); + byte[] content = content(200, 56); + failedAttempt(() -> staged().stage(stageRequest(key, content), producing(content(200, 57)))); + + // when + ObjectStageReceipt retried = staged().stage(stageRequest(key, content), producing(content)); + + // then + assertThat(retried.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(retried.contentIdentity()).isEqualTo(identityOf(content)); + } + + @Test + @DisplayName("stage 직후 복구 조회는 STAGED이고 결과는 아직 정해지지 않았다") + void aStageResolvesStaged() { + // given + ObjectOperationKey key = key("stage-phase"); + byte[] content = content(200, 37); + staged().stage(stageRequest(key, content), producing(content)); + + // when + ObjectOperationResolution resolution = resolution().resolve(key); + + // then + assertThat(resolution.state()).isEqualTo(ObjectPublicationState.STAGED); + assertThat(resolution.outcome()).isEqualTo(ObjectMutationOutcome.INDETERMINATE); + } + + @Test + @DisplayName("검증한 stage의 복구 조회는 VERIFIED이고 게시된 reference는 없다") + void aVerifiedStageResolvesVerified() { + // given + ObjectOperationKey key = key("verify-phase"); + verifiedStage(key, content(200, 58)); + + // when + ObjectOperationResolution resolution = resolution().resolve(key); + + // then + assertThat(resolution.state()).isEqualTo(ObjectPublicationState.VERIFIED); + assertThat(resolution.publishedReference()).isEmpty(); + } + + @Test + @DisplayName("검증을 다시 하면 REPLAYED다") + void verifyingAgainReplays() { + // given + ObjectOperationKey key = key("verify-replay"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 38)); + + // when + ObjectVerificationReceipt again = staged().verifyIntegrity(verify(key, stage)); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + } + + @Test + @DisplayName("다른 stage의 version으로 검증하면 거절한다") + void verifyingWithAnotherVersionIsRefused() { + // given + ObjectOperationKey key = key("verify-conflict"); + byte[] content = content(200, 39); + ObjectStageReceipt stage = staged().stage(stageRequest(key, content), producing(content)); + byte[] otherContent = content(200, 40); + ObjectStageReceipt other = + staged().stage(stageRequest(key("verify-other"), otherContent), producing(otherContent)); + + // when + Throwable refused = + catchThrowable( + () -> + staged() + .verifyIntegrity( + new ObjectVerifyRequest( + key, + stage.stageHandle(), + other.exactVersion(), + stage.contentIdentity(), + budget(), + CancellationView.never()))); + + // then + assertThat(refused).isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("claim 없이 finalize하면 거절한다") + void finalizeWithoutAClaimIsRefused() { + // given + ObjectOperationKey key = key("finalize-unclaimed"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 41)); + + // when + Throwable refused = + catchThrowable( + () -> + staged() + .finalizePublication( + new ObjectFinalizeRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + destination().publicationRequirement(), + 1, + CLAIMANT, + budget(), + CancellationView.never()))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("검증하지 않은 stage는 claim이 있어도 finalize를 거절한다") + void finalizeBeforeVerificationIsRefused() { + // given + ObjectOperationKey key = key("finalize-unverified"); + byte[] content = content(200, 42); + ObjectStageReceipt stage = staged().stage(stageRequest(key, content), producing(content)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + + // when + Throwable refused = + catchThrowable(() -> staged().finalizePublication(finalize(key, stage, claim))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("finalize를 다시 하면 같은 reference를 REPLAYED로 돌려준다") + void finalizingAgainReplays() { + // given + ObjectOperationKey key = key("finalize-replay"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 43)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + ObjectPublishReceipt first = staged().finalizePublication(finalize(key, stage, claim)); + + // when + ObjectPublishReceipt again = staged().finalizePublication(finalize(key, stage, claim)); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + assertThat(again.reference()).isEqualTo(first.reference()); + } + + @Test + @DisplayName("처음 claim하면 APPLIED다") + void aFirstClaimIsApplied() { + // given + ObjectOperationKey key = key("claim-first"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 59)); + + // when + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + + // then + assertThat(claim.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(claim.fence()).isPositive(); + } + + @Test + @DisplayName("같은 claimant가 다시 claim하면 같은 fence를 REPLAYED로 돌려준다") + void reclaimingByTheSameClaimantReplays() { + // given + ObjectOperationKey key = key("claim-replay"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 44)); + ObjectHandoffReceipt first = claim(key, stage, CLAIMANT); + + // when + ObjectHandoffReceipt again = claim(key, stage, CLAIMANT); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + assertThat(again.fence()).isEqualTo(first.fence()); + } + + @Test + @DisplayName("다른 claimant는 살아 있는 claim을 가져가지 못한다") + void anotherClaimantCannotTakeAnActiveClaim() { + // given + ObjectOperationKey key = key("claim-contended"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 45)); + claim(key, stage, CLAIMANT); + + // when + Throwable refused = catchThrowable(() -> claim(key, stage, "worker-b")); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("claim을 연장하면 같은 fence로 APPLIED다") + void renewingKeepsTheFence() { + // given + ObjectOperationKey key = key("claim-renew"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 46)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + + // when + ObjectHandoffReceipt renewed = + handoff() + .renewClaim( + new ObjectHandoffRenewRequest( + key, + stage.stageHandle(), + claim.fence(), + CLAIMANT, + LEASE, + budget(), + CancellationView.never())); + + // then + assertThat(renewed.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(renewed.fence()).isEqualTo(claim.fence()); + } + + @Test + @DisplayName("놓은 claim은 다른 claimant가 다음 fence로 가져간다") + void aReleasedClaimIsTakenAtTheNextFence() { + // given + ObjectOperationKey key = key("claim-handover"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 47)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + release(key, stage, claim); + + // when + ObjectHandoffReceipt taken = claim(key, stage, "worker-b"); + + // then + assertThat(taken.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(taken.fence()).isGreaterThan(claim.fence()); + } + + @Test + @DisplayName("같은 claim을 다시 놓으면 REPLAYED다") + void releasingAgainReplays() { + // given + ObjectOperationKey key = key("release-replay"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 48)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + release(key, stage, claim); + + // when + ObjectMutationReceipt again = release(key, stage, claim); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + } + + @Test + @DisplayName("살아 있는 claim이 있으면 중단을 허가하지 않는다") + void anActiveClaimRefusesAbortAuthorization() { + // given + ObjectOperationKey key = key("abort-active"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 49)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + + // when + Throwable refused = + catchThrowable(() -> handoff().authorizeAbort(authorization(key, stage, claim))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("놓은 claim에 중단을 허가하면 APPLIED다") + void aReleasedClaimAuthorizesAbort() { + // given + ObjectOperationKey key = key("abort-authorize"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 60)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + release(key, stage, claim); + + // when + ObjectMutationReceipt authorized = handoff().authorizeAbort(authorization(key, stage, claim)); + + // then + assertThat(authorized.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + } + + @Test + @DisplayName("허가된 중단은 stage를 중단하고 복구 조회는 ABORTED다") + void anAuthorizedAbortAbortsTheStage() { + // given + ObjectOperationKey key = key("abort-authorized"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 50)); + ObjectAbortAuthorization authorization = releasedAndAuthorized(key, stage); + + // when + ObjectMutationReceipt aborted = staged().abort(abort(key, stage, authorization)); + + // then + assertThat(aborted.outcome()).isEqualTo(ObjectMutationOutcome.APPLIED); + assertThat(resolution().resolve(key).state()).isEqualTo(ObjectPublicationState.ABORTED); + } + + @Test + @DisplayName("같은 중단을 다시 하면 REPLAYED다") + void abortingAgainReplays() { + // given + ObjectOperationKey key = key("abort-replay"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 51)); + ObjectAbortAuthorization authorization = releasedAndAuthorized(key, stage); + staged().abort(abort(key, stage, authorization)); + + // when + ObjectMutationReceipt again = staged().abort(abort(key, stage, authorization)); + + // then + assertThat(again.outcome()).isEqualTo(ObjectMutationOutcome.REPLAYED); + } + + @Test + @DisplayName("중단한 stage는 바이트가 없어 검증을 거절한다") + void anAbortedStageCannotBeVerified() { + // given + ObjectOperationKey key = key("abort-then-verify"); + byte[] content = content(200, 61); + ObjectStageReceipt stage = staged().stage(stageRequest(key, content), producing(content)); + staged().abort(abort(key, stage, releasedAndAuthorized(key, stage))); + + // when + Throwable refused = catchThrowable(() -> staged().verifyIntegrity(verify(key, stage))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("검증한 뒤 중단한 stage도 검증을 거절한다") + void aVerifiedThenAbortedStageCannotBeVerifiedAgain() { + // given + ObjectOperationKey key = key("verify-then-abort"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 63)); + staged().abort(abort(key, stage, releasedAndAuthorized(key, stage))); + + // when + Throwable refused = catchThrowable(() -> staged().verifyIntegrity(verify(key, stage))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("중단 허가 없이 중단하면 거절한다") + void abortWithoutAuthorizationIsRefused() { + // given + ObjectOperationKey key = key("abort-unauthorized"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 52)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + release(key, stage, claim); + + // when + Throwable refused = + catchThrowable(() -> staged().abort(abort(key, stage, authorization(key, stage, claim)))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("게시된 stage는 중단 허가를 CONFLICT로 거절한다") + void aPublishedStageRefusesAbortAuthorization() { + // given + ObjectOperationKey key = key("abort-published-authorize"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 53)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + staged().finalizePublication(finalize(key, stage, claim)); + + // when + ObjectMutationReceipt refused = handoff().authorizeAbort(authorization(key, stage, claim)); + + // then + assertThat(refused.outcome()).isEqualTo(ObjectMutationOutcome.REJECTED); + assertThat(refused.error()).isEqualTo(ObjectOperationError.CONFLICT); + } + + @Test + @DisplayName("게시된 stage는 중단을 거절한다") + void aPublishedStageCannotBeAborted() { + // given + ObjectOperationKey key = key("abort-published"); + ObjectStageReceipt stage = verifiedStage(key, content(200, 62)); + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + staged().finalizePublication(finalize(key, stage, claim)); + + // when + Throwable refused = + catchThrowable(() -> staged().abort(abort(key, stage, authorization(key, stage, claim)))); + + // then + assertThat(refused).isInstanceOf(IllegalStateException.class); + } + + /** Claims {@code stage}, releases the claim and authorizes the abort at its fence. */ + protected final ObjectAbortAuthorization releasedAndAuthorized( + ObjectOperationKey key, ObjectStageReceipt stage) { + ObjectHandoffReceipt claim = claim(key, stage, CLAIMANT); + release(key, stage, claim); + ObjectAbortAuthorization authorization = authorization(key, stage, claim); + handoff().authorizeAbort(authorization); + return authorization; + } + + /** A staged and verified copy of {@code content} under {@code key}. */ + protected final ObjectStageReceipt verifiedStage(ObjectOperationKey key, byte[] content) { + ObjectStageReceipt stage = staged().stage(stageRequest(key, content), producing(content)); + staged().verifyIntegrity(verify(key, stage)); + return stage; + } + + /** The verification of {@code stage} as staged. */ + protected static ObjectVerifyRequest verify(ObjectOperationKey key, ObjectStageReceipt stage) { + return new ObjectVerifyRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + stage.contentIdentity(), + budget(), + CancellationView.never()); + } + + /** {@code claimant}'s publication claim on {@code stage}. */ + protected final ObjectHandoffReceipt claim( + ObjectOperationKey key, ObjectStageReceipt stage, String claimant) { + return handoff() + .claimForPublication( + new ObjectHandoffClaimRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + claimant, + LEASE, + budget(), + CancellationView.never())); + } + + /** The finalize that {@link #CLAIMANT}'s {@code claim} allows. */ + protected final ObjectFinalizeRequest finalize( + ObjectOperationKey key, ObjectStageReceipt stage, ObjectHandoffReceipt claim) { + return new ObjectFinalizeRequest( + key, + stage.stageHandle(), + stage.exactVersion(), + destination().publicationRequirement(), + claim.fence(), + CLAIMANT, + budget(), + CancellationView.never()); + } + + protected final ObjectMutationReceipt release( + ObjectOperationKey key, ObjectStageReceipt stage, ObjectHandoffReceipt claim) { + return handoff() + .releaseClaim( + new ObjectHandoffReleaseRequest( + key, + stage.stageHandle(), + claim.fence(), + CLAIMANT, + budget(), + CancellationView.never())); + } + + protected static ObjectAbortAuthorization authorization( + ObjectOperationKey key, ObjectStageReceipt stage, ObjectHandoffReceipt claim) { + return new ObjectAbortAuthorization( + key, stage.stageHandle(), stage.exactVersion(), claim.fence(), Instant.now()); + } + + protected static ObjectAbortRequest abort( + ObjectOperationKey key, ObjectStageReceipt stage, ObjectAbortAuthorization authorization) { + return new ObjectAbortRequest( + key, stage.stageHandle(), authorization, budget(), CancellationView.never()); + } +} From 3e1c629d1f7b8105f4990bb081bd789b02127f66 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 15:02:10 +0900 Subject: [PATCH 4/5] =?UTF-8?q?docs(rules):=20=EA=B3=B5=EC=9C=A0=20?= =?UTF-8?q?=EA=B3=84=EC=95=BD=20=ED=85=8C=EC=8A=A4=ED=8A=B8=EB=8A=94=20?= =?UTF-8?q?=ED=8F=AC=ED=8A=B8=EA=B0=80=20=EC=84=A0=EC=96=B8=ED=95=9C=20?= =?UTF-8?q?=EA=B2=83=EB=A7=8C=20=EB=8B=A8=EC=96=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 시험 규칙 5는 예외 메시지까지 단언하라고 했다. fake와 adapter가 함께 상속하는 계약에서는 메시지가 구현마다 달라 그 규칙을 따를 수 없다. TESTING_STRATEGY 9.4가 이미 그렇게 정했는데 규칙 문서가 가리키지 않아, 다음 작성자가 메시지 단언을 다시 넣을 수 있었다. Refs: RR9-03-31 --- .claude/rules/java-tests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/rules/java-tests.md b/.claude/rules/java-tests.md index 03f56897..9d993bc9 100644 --- a/.claude/rules/java-tests.md +++ b/.claude/rules/java-tests.md @@ -16,7 +16,7 @@ paths: 2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만 쓰고, 한국어로 쓴다(2026-09-25 소유자 결정). 기존 영어 `@DisplayName`은 그 테스트 메서드를 고칠 때 한국어로 바꾼다. 같은 클래스의 고치지 않은 메서드는 바꾸지 않아도 되고, 바꾸면 같은 커밋에 넣고 보고에 적는다. 3. 본문 문장이 3개 이상이면 `// given` `// when` `// then` 주석과 구역 사이 빈 줄을 둔다. 준비할 것이 없으면 `// given`은 생략한다. `// when`은 정확히 하나다. 두 번 필요하면 테스트를 나눈다. 예외 테스트는 `catchThrowable`로 when을 분리한다(기존 `assertThatThrownBy`는 손댈 때 `// when & then`까지 허용). 한 줄 테스트와 ArchUnit `.check()`는 주석 없이 쓴다. 4. `@Nested`는 테스트 10개 이상이고 대상 연산이 2개 이상인 클래스에서만, 연산 단위로 한 단계만 쓴다. -5. then은 when의 결과 하나만 단언한다. 여러 필드는 `usingRecursiveComparison()` 또는 `extracting(..).containsExactly(..)`로 한 번에 비교한다. `isNotNull`·`isPresent`·`doesNotThrowAnyException`만으로 끝내지 않는다(이름이 "예외 없음" 자체를 말할 때만 예외). 예외는 타입과 reason·message를 함께 단언한다. 표 형태 입력은 `@ParameterizedTest`로 쓴다. +5. then은 when의 결과 하나만 단언한다. 여러 필드는 `usingRecursiveComparison()` 또는 `extracting(..).containsExactly(..)`로 한 번에 비교한다. `isNotNull`·`isPresent`·`doesNotThrowAnyException`만으로 끝내지 않는다(이름이 "예외 없음" 자체를 말할 때만 예외). 예외는 타입과 reason·message를 함께 단언한다. 다만 fake와 adapter가 함께 상속하는 계약 테스트(`XxxContract`)는 포트가 선언한 것만 단언한다. 포트 Javadoc이 메시지를 정하지 않으면 타입만 본다. 표 형태 입력은 `@ParameterizedTest`로 쓴다. 6. 포트 대역은 hand-rolled fake를 포트당 하나, 포트 소유 모듈 testFixtures에 둔다. adapter가 있는 포트는 fake와 adapter가 같은 추상 계약 테스트(`XxxContract`)를 통과한다. Mockito는 프레임워크 경계(Spring Data repository, SDK client)와 장애 주입에만 쓴다. GWT 주석을 검사하는 자동 게이트는 만들지 않는다. 주석은 bytecode에 없어 ArchUnit이 볼 수 없고, 실질적인 강제 수단은 fake와 adapter가 같은 계약 테스트를 상속하는 구조다. From d95e8dc0f9f525f155ab17fa21562001c46dd660 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 15:09:33 +0900 Subject: [PATCH 5/5] =?UTF-8?q?docs(upgrade):=20objectstorage=20=ED=8F=AC?= =?UTF-8?q?=ED=8A=B8=20=EA=B3=84=EC=95=BD=EC=9D=B4=20=EB=B0=94=EA=BE=BC=20?= =?UTF-8?q?=EA=B2=B0=EA=B3=BC=EB=A5=BC=20=ED=8C=8C=EC=83=9D=20=EC=84=9C?= =?UTF-8?q?=EB=B9=84=EC=8A=A4=EC=97=90=20=EC=95=8C=EB=A6=B0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 실패한 managed 게시를 다시 하면 APPLIED가 되고, 중단한 stage의 재검증은 IllegalStateException이 되며, 불변 Set capability가 동작한다. 이 셋과 testFixtures의 fake·계약을 쓰는 법을 업그레이드 안내에 적는다. Refs: RR9-03-31, RR9-03-33, RR9-03-35 --- docs/upgrade/2026-11-round9-objectstorage.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 docs/upgrade/2026-11-round9-objectstorage.md diff --git a/docs/upgrade/2026-11-round9-objectstorage.md b/docs/upgrade/2026-11-round9-objectstorage.md new file mode 100644 index 00000000..284c3e0a --- /dev/null +++ b/docs/upgrade/2026-11-round9-objectstorage.md @@ -0,0 +1,19 @@ +# 업그레이드 안내 — 2026-11 objectstorage 포트 계약 + +- 범위: `application-objectstorage` 포트의 결과와 거절을 포트 Javadoc에 적고, fake와 local-dev adapter가 같은 계약 + 시험을 통과하게 맞춘 변경. 결과가 바뀐 호출이 셋 있다. 아래 표가 그 목록이다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 objectstorage 포트 계약 발견 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받으면서 객체 저장소 포트(`ManagedObjectPublicationPort` 등)를 쓰는 +파생 서비스가 읽는다. 포트를 쓰지 않으면 할 일이 없다. + +## 2. 할 일 + +| # | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | 실패한 managed 게시를 같은 operation key로 다시 했을 때의 결과를 확인한다. 이제 이번 호출이 게시를 끝냈으면 `APPLIED`다(전에는 `REPLAYED`). 같은 key로 겹친 호출은 `PUBLISHED`로 바꾼 하나만 `APPLIED`다 | 재시도 결과가 `REPLAYED`라고 보고 분기하던 코드가 다른 길로 간다 | `ManagedObjectPublicationPort.publish`를 재시도하는 서비스 | +| 2 | 중단한 stage를 다시 검증하지 않는다. 이제 `verifyIntegrity`가 `IllegalStateException`으로 거절한다(전에는 검증 뒤 중단한 stage를 다시 검증하면 `REPLAYED`) | 그 호출이 예외로 끝난다 | `StagedObjectPublicationPort`를 쓰는 서비스 | +| 3 | 불변 `Set`(`Set.of`)으로 capability를 넘겨도 된다. 전에는 요청을 만들 때 `NullPointerException`이 났다 | — 고치기만 한 변경 | 게시·stage 요청을 만드는 서비스 | +| 4 | 유스케이스 시험에서 포트 대역이 필요하면 `testImplementation testFixtures(project(':application-objectstorage'))`로 `InMemoryObjectStorage`와 포트 계약을 쓴다 | — 더하기만 한 변경 | 객체 저장소를 쓰는 유스케이스를 시험하는 서비스 |